[英]Passing arguments java8
I have a method doStuff(String arg1). 我有一个方法doStuff(String arg1)。 I invoke it from the object someObject, passing it the "constant name" as the String argument.
我从对象someObject调用它,并将“常量名”作为String参数传递给它。 Can I get the value of this variable inside the doStuff method?
我可以在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").
}
try this : someObject.doStuff(Class2.SOME_CONST);
试试这个:
someObject.doStuff(Class2.SOME_CONST);
instead of someObject.doStuff("SOME_CONST");
而不是
someObject.doStuff("SOME_CONST");
Not completely sure what you're asking but you can get the value by reflection, like this. 不能完全确定您要问的是什么,但是您可以像这样通过反思获得价值。 (It will print CONSTANT)
(它将打印恒定)
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();
}
}
}
If you want to pass the attribute : SOME_CONST
如果要传递属性:
SOME_CONST
public static final String SOME_CONST = "someString";
As a parameter for : doMoreStuff(...)
You need to write this : doMoreStuff(SOME_CONST);
作为:
doMoreStuff(...)
的参数,您需要编写以下代码: doMoreStuff(SOME_CONST);
Because doMoreStuff("SOME_COST");
因为
doMoreStuff("SOME_COST");
will pass as parameter the String "SOME_COST"
and not the variable 将传递参数
String "SOME_COST"
而不是变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.