switch (from) {
case TAGs.casts://constant expression required
break;
}
//我的TAGs.casts是这样的
public interface TAGs {
String casts = String.class.getSimpleName();
}
//如果写成这个样子就可以编译
public interface TAGs {
String casts = "String";
}
Isn’t it said that the member variables in the interface are constants? Why can't I use the prompt to require constants on the case?
When using an interface, you must assign an initial value to the constant. If you write it yourself without giving an initial value, it must be wrong.
The case in switch needs to determine the value at compile time, and String.class.getSimpleName(); needs to be known at run time (although it is indeed a constant at run time), so the compilation cannot pass
Indeed. One is required at compile time, and the other is runtime (reflection methods are all runtime). I answered it wrong before - when I looked at effective java, it was modified by static final. There is also a suggestion in it, please use enumeration class to export constants.
Didn’t it mean that the member variables in the interface are all constants? Where did you hear this sentence?
Constants need to be modified withstatic final
and need to be given an initial value