我在第三方JAR中有一个设计很差的类,我需要访问它的一个私有字段。例如, 为什么我需要选择私人领域是必要的?
class IWasDesignedPoorly {
private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
如何使用反射来获取stuffIWant的值?
我在第三方JAR中有一个设计很差的类,我需要访问它的一个私有字段。例如, 为什么我需要选择私人领域是必要的?
class IWasDesignedPoorly {
private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
如何使用反射来获取stuffIWant的值?
当前回答
如果使用Spring:
在测试上下文中,ReflectionTestUtils提供了一些方便的工具,可以以最小的工作量帮助解决这个问题。它被描述为“用于单元和集成测试场景”。
在非测试上下文中,还有一个类似的类,名为ReflectionUtils,但它被描述为“仅供内部使用”——请参阅下面的回答,以更好地解释它的含义。
要解决原文中的例子:
Hashtable iWantThis = (Hashtable)ReflectionTestUtils.getField(obj, "stuffIWant");
其他回答
试试Apache common -lang3中的FieldUtils:
FieldUtils.readField(object, fieldName, true);
附注:在我看来,反思是邪恶的。
您可以使用jOOR来实现这一点。
class Foo {
private final String value = "ABC";
}
class Bar {
private final Foo foo = new Foo();
public String value() {
return org.joor.Reflect
.on(this.foo)
.field("value")
.get();
}
}
class BarTest {
@Test
void accessPrivateField() {
Assertions.assertEquals(new Bar().value(), "ABC");
}
}
正如oxbow_lakes提到的,您可以使用反射来绕过访问限制(假设您的SecurityManager允许您)。
也就是说,如果这门课设计得如此糟糕,以至于你不得不求助于这样的伎俩,也许你应该寻找另一种选择。当然,这个小技巧现在可能会为你节省几个小时,但它会让你付出多少代价呢?
使用XrayInterface工具非常简单。只需定义缺失的getter /setter,例如:
interface BetterDesigned {
Hashtable getStuffIWant(); //is mapped by convention to stuffIWant
}
用x射线照射你设计糟糕的项目:
IWasDesignedPoorly obj = new IWasDesignedPoorly();
BetterDesigned better = ...;
System.out.println(better.getStuffIWant());
在内部,这依赖于反思。
尝试绕过这种情况下的问题,您想要设置/获取数据的类是您自己的类之一。
只需为此创建一个公共setter(Field f, Object value)和公共Object getter(Field f)。您甚至可以在这些成员函数中自己进行一些安全检查。例如,对于setter:
class myClassName {
private String aString;
public set(Field field, Object value) {
// (A) do some checkings here for security
// (B) set the value
field.set(this, value);
}
}
当然,现在你必须在设置字段值之前为sString找到java.lang.reflect.Field。
我确实在一个通用的resultset -to-and-from-model- mapping器中使用了这种技术。