【发布时间】:2009-07-07 12:51:46
【问题描述】:
我有一个看起来像这样的实体:(我正在对网页进行编码,因此对于任何错误,我深表歉意)
@Entity
public class Entity {
@Id
private Long id;
private String field;
// Insert getters and setters here...
}
我尝试使用反射来操纵它:
Long id = 1;
Entity entity = myDao.getEntity(id);
entity.setField("set directly");
Field[] fields = entity.getClass().getDeclaredFields();
for (Field f : fields) {
if (f.getName().equals("field")) {
f.setAccessible(true);
f.set(entity, "set using reflection");
f.setAccessible(false);
}
}
System.out.println(entity.getField());
这个程序打印“使用反射设置”。但是,在数据库中使用反射设置的值不会更新:
SELECT * FROM ENTITY WHERE ID = 1
ID FIELD
1 set directly
这很奇怪。我可以发誓这曾经有效——但现在不行了。是不是真的不能使用反射来操作实体?
如果这很重要,我正在使用 EclipseLink 1.1.1。
【问题讨论】:
标签: java reflection jpa