【发布时间】:2017-06-02 21:20:44
【问题描述】:
早上好。我通过反射从类的字段中获取值。我通过参数获取对象,但是当我显示我得到的值时,它是空白的。我得到了属性,但没有得到值。从我注意到的情况来看,它似乎没有捕获传递的对象的实例。感谢您的帮助。
public static void transformarCamposCaixaAlta(BaseModel bm) {
Class<?> classe = bm.getClass();
for(Field item : classe.getDeclaredFields()) {
item.setAccessible(true);
if (item.getType() == BaseModel.class) {
try {
transformarCamposCaixaAlta((BaseModel) item.get(bm));
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (item.isAnnotationPresent(FieldUpperCase.class)) {
try {
if(item.get(bm) != null) {
System.out.println("Valor: "+ item.get(bm).toString() + " Tipo: "+ item.getName());
System.out.println("------");
item.set(bm, ((String)item.get(bm)).toUpperCase());
}
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
"...它是空白的"你能详细说明一下,数据类型是什么?
-
你试过minimal reproducible example吗?这对我来说看起来不错,所以检查一下使用的实例可能
-
是的,我用最少的示例和功能进行了测试。
-
请向minimal reproducible example 明确说明实际行为和预期行为。
-
顺便说一句,如果你想检查每个类型
item.getType() == BaseModel.class将无法管理子类。循环通过Class.getGenericSuperclass可以提供帮助,
标签: java reflection