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
{
thrownew NoSuchFieldException(fieldName);
}
}
注:这是一个简单实现,实际中需要优化。
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/