我很好奇是否可以存储 Field 对象的实例并将其用于我传递给它的任何对象。我正在做大量的反射工作,我记得在某处读过,存储 Field 对象并将其用作单例(或多或少)来快速从类访问该字段是不安全的。
这实际上可能吗,或者我正在尝试做的事情在任何方面都是危险的或有缺陷的?我做了一个快速测试来检查,它似乎有效......但我不确定这个测试是否真的证明了这一点。
这假设我们被允许访问该字段并且不会引发 SecurityException。
<小时/>用于测试的代码:
package test;
import java.lang.reflect.Field;
public class TestClass {
public static void main(String[] args) {
Field fa = null;
Field fb = null;
for (Field f : Test.class.getDeclaredFields()) {
switch (f.getName()) {
case "a":
fa = f;
break;
case "b":
fb = f;
break;
}
}
fa.setAccessible(true);
fb.setAccessible(true);
Test ta = new Test(5, "test");
Test tb = new Test(54, "new string");
try {
System.out.println(fa.get(ta) + " " + fa.get(tb) + " " + fb.get(ta) + " " + fb.get(tb));
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("unused")
class Test {
private int a;
private String b;
public Test(int a, String b) {
this.a = a;
this.b = b;
}
}
产量:
5 54 test new string
最佳答案
这完全没问题,而且应该以这种方式工作。 Field
指的是特定类中的字段,而不是该类的特定实例(对象) - 因此您可以将它与该类的任何实例一起使用。
当然,如果Field
引用类Test
中的字段,那么您只能在Test
类型的对象上使用它。如果您尝试在 Field
上调用 get(Object o)
,向其传递除 Test 之外的其他内容,则会收到
对象。IllegalArgumentException
参见Field.get(Object o)
的API文档.
关于java - Java 反射中的 Field 类可以作用于任何对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323637/