我有一个方法doStuff(String arg1)。我从对象someObject调用它,将“常量名称”作为字符串参数传递给它。我能在doStuff方法中得到这个变量的值吗?
public Class1 {
someObject.doStuff("SOME_CONST");
}
public Class2 {
public static final String SOME_CONST = "someString";
public void doStuff(String arg1) {
doMoreStuff(arg1);
}
// expected: doMoreStuff("someString"), but actual:
doMoreStuff("SOME_CONST").
}
发布于 2017-07-18 20:15:59
不完全确定你所要求的是什么,但是你可以通过反射获得值,就像这样。(它将打印常量)
public static class Class1 {
public static void main(String[] args) {
new Class2().doStuff("SOME_CONST");
}
}
public static class Class2 {
public static final String SOME_CONST = "CONSTANT";
public void doStuff(String const_name) {
try {
String const_value = (String) Class2.class.getDeclaredField(const_name).get(null);
System.out.println(const_value);
}catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
发布于 2017-07-18 20:09:18
试试这个:用someObject.doStuff(Class2.SOME_CONST);
代替someObject.doStuff("SOME_CONST");
发布于 2017-07-18 20:06:36
如果您想要传递属性:SOME_CONST
public static final String SOME_CONST = "someString";
作为:doMoreStuff(...)
的参数,您需要编写以下代码:doMoreStuff(SOME_CONST);
因为doMoreStuff("SOME_COST");
将作为参数传递String "SOME_COST"
而不是变量
https://stackoverflow.com/questions/45166273
复制相似问题