为什么全局变量不会在同一个全局变量中使用全局函数更新? 安卓/ Java的

对于android中的应用程序,我有一个全局变量,

public class ConstantsUrls { public static String GET_CART_ALL_ITEM = "store/3/cart/" + CartFunctions.ReturnUserRrQuote() + "/type/customer" } 

并且,

 public class CartFunctions { public static String ReturnUserRrQuote() { String user_value = ""; //some function return user_value; } } 

当我调用一个函数时,让A使用参数ConstantsUrls.GET_CART_ALL_ITEM作为

 A(ConstantsUrls.GET_CART_ALL_ITEM); 

我得到正确的值作为store/3/cart/100/type/customer但是当我再次打电话时

具有相同参数的函数A我总是得到与store/3/cart/100/type/customer完全相同的值,即使ReturnUserRrQuote()没有调用第二次获取更新值。

当我调用该函数时

A("store/3/cart/" + CartFunctions.ReturnUserRrQuote() + "/type/customer")

代替

 A(ConstantsUrls.GET_CART_ALL_ITEM); 

我总是得到正确的工作(更新正确的值)

为什么全局变量不会在同一个全局变量中使用全局函数进行更新。 这个Java核心的行为是这样还是其他任何原因?

在您的代码中,创建常量GET_CART_ALL_ITEM并仅初始化一次,并且它采用ReturnUserRrQuote()的当前值。 稍后它不会触发该函数,因为常量已经具有其值并且不需要新的初始化。

如果在代码的开头ReturnUserRrQuote() =>“100”。 然后创建GET_CART_ALL_ITEM并使用此值初始化,它将是"store/3/cart/100/type/customer"而不是"store/3/cart/" + ReturnUserRrQuote() + "/type/customer" 。 它是初始化的原因,表达式"store/3/cart/" + ReturnUserRrQuote() + "/type/customer"被评估,结果受常量影响(表达式不受常量影响)。

因此,当您稍后调用此常量时,假定ReturnUserRrQuote() =>“250”。 GET_CART_ALL_ITEM仍为"store/3/cart/100/type/customer" 。 您没有重新定义它以包含ReturnUserRrQuote()的新值(并且您不希望java这样做或它不会是常量)。

在你的情况下要么你想要一个常数,所以每当ReturnUserRrQuote()改变时它都不会改变是正常的。 或者你希望它每次重新评估,你不想要一个常数。 你可以这样做:

 public static final const1 = "store/3/cart/"; public static final const2 = "/type/customer"; //whenever you have to obtain your value String value = const1 + ReturnUserRrQuote() + const2; 

编辑:你说的是全局变量而不是常数,但问题是一样的。 即使有非全局变量。

 //Static function that return the number of times it has been called public static returnNumber() { final int i=1; return i++; } public static void main() { int a = returnNumber(); //Initialize a for (j=0; j<10; j++) { System.out.println(a); //print the current value of a } } 

在这个例子中,a将在main的开头初始化。 将评估表达式returnNumber()并将结果影响到a。 这是第一次调用returnNumber然后结果是1.所以a的值是1而不是returnNumber() 。 在循环中我调用了10次并打印出来。 10次​​a将值1,数字1将打印10次。 每次调用时它都不会调用returnNumber()