简体   繁体   English

Java无法从同一类中获取静态变量的值

[英]java unable to get value of static variable from the same class

I have a AppConstants class where I have some static variables and static methods. 我有一个AppConstants类,其中有一些静态变量和静态方法。 Variable like 像变量

public static final String BASE_URL = "http://www.somevalue.com/api/";
private static String MID_FIX_API;
public static final String API_CALL = BASE_URL + getMidFixApi() + "/" + GET_KEY(appContext, KEY_FOR_KEY);

As MID_FIX_API is private so I have its public getter/setter. 由于MID_FIX_API是私有的,所以我有其公共获取者/设置者。 When I set its value from another class by its setter method AppConstants.setMidFixApi("value"); 当我通过其设置方法AppConstants.setMidFixApi("value");从另一个类设置其值时AppConstants.setMidFixApi("value"); and get its value from its getter method AppConstants.getMidFixApi(); 并从其吸气方法AppConstants.getMidFixApi();获取其值AppConstants.getMidFixApi(); Everything is fine till now 到目前为止一切都很好
But
The problem comes when after the above lines I call static variable API_CALL shown in the code above that get value from the getter of the variable MID_FIX_API and return null despite of that we have passed value to it before. 问题出在上面的代码行之后,我调用了上面代码中显示的静态变量API_CALL ,即从变量MID_FIX_API的getter获取值,并且尽管我们之前已将值传递给它,但仍返回null。

This is the whole sequence of lines 这是整行的顺序

AppConstants.setMidFixApi("getCategories");   // setting value
Log.e("InsideSuccess", "MID_FIX_API = " + AppConstants.getMidFixApi());  // working fine till here

Log.e("InsideSuccess", "API_URL = "+AppConstants.API_CALL);   // here I'm getting like this http://www.somevalue.com/api/null/somePostFix

Please point me what I'm doing wrong. 请指出我做错了什么。

This has to to with initialisation order. 这必须与初始化顺序有关。 When you call AppConstants.setMidFixApi("getCategories") the AppConstants class will be initialised before the value is set. 当您调用AppConstants.setMidFixApi("getCategories") ,将设置值之前初始化AppConstants类。 Hence when the API_CALL is initialised, the MID_FIX_API is not yet assigned... 因此,当初始化API_CALL时,尚未分配MID_FIX_API ...

As already mentioned the variable API_CALL is initialized once, with the current value of MID_FIX_API which initially is null. 如前所述,变量API_CALL初始化一次,其初始值为MID_FIX_API的当前值。

A work around is to create a static method ( getApiCall() ) which just computes the value which earlier was staticly initialized, which would just look as easy as this: 解决方法是创建一个静态方法( getApiCall() ),该方法仅计算先前静态初始化的值,该方法看起来像这样简单:

public static String getApiCall(){
    return BASE_URL + getMidFixApi() + "/" + GET_KEY(appContext, KEY_FOR_KEY);
}

Which then can be called in an easy manner AppConstants.getApiCall() . 然后可以通过简单的方法AppConstants.getApiCall()进行调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM