附:注入私有属性的实现:
publicvoid setFieldObject(Object instance, String fieldName, Object value)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException {
Field field = null;
Class c = instance.getClass();
do {
try
{
field = c.getDeclaredField(fieldName);
} catch (SecurityException e)
{
e.printStackTrace();
} catch (NoSuchFieldException e)
{
c = c.getSuperclass();
}
}
while (c.getName() != "java.lang.Object" && field == null);
if (field != null)
{
field.setAccessible(true);
field.set(instance, value);
}
else
{
new NoSuchFieldException(fieldName);
}
}
注:这是一个简单实现,实际中需要优化。
文章来源于领测软件测试网 https://www.ltesting.net/