使用Java Reflection,是否可以获取局部变量的名称?例如,如果我有这个:
Foo b = new Foo();
Foo a = new Foo();
Foo r = new Foo();
Run Code Online (Sandbox Code Playgroud)
是否可以实现一个可以找到这些变量名称的方法,如下所示:
public void baz(Foo... foos)
{
for (Foo foo: foos) {
// Print the name of each foo - b, a, and r
System.out.println(***);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个问题不同于Java有没有办法找到传递给函数的变量的名称?因为它更纯粹地询问关于是否可以使用反射来确定局部变量的名称的问题,而另一个问题(包括接受的答案)更侧重于测试变量的值.
是否可以使用Java Reflection打印出父类的属性.
我正在学习java反思.我试过了
System.exit(3);
Class.forName("java.lang.System").getMethod("exit", Integer.TYPE).invoke(null, 3);
它的工作原理.我成功也跑了
System.out.println(Class.forName("java.lang.System").getMethod("currentTimeMillis").invoke(null));
现在我如何反思地调用System.out.println
java.lang.Class.forName("java.lang.System").getMethod("out.println", String.class).invoke(null, "Hi!");
给出错误.我知道系统没有功能.因此,建议一种反射性地调用System.out.println的方法
这是完整的例子
public class ReflectionDemo1 {
public static void main(String[] args) throws Exception {
// java.lang.System.exit(3);
// java.lang.Class.forName("java.lang.System").getMethod("exit", Integer.TYPE).invoke(null, 3);
// java.lang.System.currentTimeMillis()
// System.out.println(Class.forName("java.lang.System").getMethod("currentTimeMillis").invoke(null));
// System.out.println("Hi!");
java.lang.Class.forName("java.lang.System").getMethod("out.println", String.class).invoke(null, "Hi!");
}
}
Run Code Online (Sandbox Code Playgroud)