java field 获得值_反射通用获取字段值
像之前回答的那樣,您應該使用:
Object value = field.get(objectInstance);
有時更喜歡的另一種方法是動態調用getter。示例代碼:
public static Object runGetter(Field field, BaseValidationObject o)
{
// MZ: Find the correct method
for (Method method : o.getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
// MZ: Method found, run it
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
catch (InvocationTargetException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
}
}
}
return null;
}
還應注意,當您的類繼承自另一個類時,您需要遞歸確定Field。例如,獲取給定類的所有字段;
for (Class> c = someClass; c != null; c = c.getSuperclass())
{
Field[] fields = c.getDeclaredFields();
for (Field classField : fields)
{
result.add(classField);
}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java field 获得值_反射通用获取字段值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux gst qt,【ARM-Li
- 下一篇: RGB网页颜色在线取色器