如何从其他类方法变量设置全局变量?

问题描述 投票:0回答:1

我想将值设置为全局变量,需要访问任何类文件。

Country.java:

public class Country {
    public String getMobileCode() throws SQLException, Exception{
       /* MySQL Conn part
        String cCode = rs.getString("COUNTRY_CODE");
       */
        if(cCode.equals("IN")){
            PHONE_NO_PREFIX = "91";
        }else{
            PHONE_NO_PREFIX = "33";
        }
        return PHONE_NO_PREFIX;
    }
}

注册Java:

public class Register { 
    public static Country CountryBO = new Country();
    public static String PHONE_NO_PREFIX = CountryBO.getMobileCode();  // error: Unhandled exception type Exception

    public static String getPhone(String _message) {
         String Pattern = PHONE_NO_PREFIX;
   }
}

如何在任何类中访问PHONE_NO_PREFIX并将其定义为全局变量?

java variables global
1个回答
0
投票

您可以使用静态初始化块,这将使您可以使用try / catch块

...
public static String PHONE_NO_PREFIX;

static {
    try {
        PHONE_NO_PREFIX = CountryBO.getMobileCode();
    } catch (Exception e) {
        // TODO Handle the exception here
    }
}

如果将PHONE_NO_PREFIX设置为final(您可能想这样做),则可以使用局部静态方法:

public static final String PHONE_NO_PREFIX = getCountryCode();
private static String getCountryCode() {
    try {
        return CountryBO.getMobileCode();
    } catch (Exception e) {
        // TODO Handle the exception here
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.