【问题标题】:get value from private field having object "Field". JAVA从具有对象“字段”的私有字段中获取值。 JAVA
【发布时间】:2011-11-13 12:56:03
【问题描述】:

我的问题是,我想使用 Hibernate 将类对象 java.lang.reflect.Field 保存到数据库中。 例如。表:

@Entity
public class Actor implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }
}

我有条件表,我想通过字符串存储 java.lang.reflect.Field 对象:

@Entity
public class Conditions implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    private String value;
    private String field;
    private int type;

    public void setField(String field) {
        this.field = field;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getField() {
        return field;
    }

    public int getType() {
        return type;
    }

    public String getValue() {
        return value;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }
}

现在我会做这样的事情:

Conditions con;
// con = get our condition from database (via hibernate)
java.lang.reflect.Field f = Actor.class.getDeclaredField(con.getField());
Actor a = new Actor();
a.setName("My name");
String ActorName = f.get(a);

这是我的问题,现在我得到了类似的异常:

java.lang.IllegalAccessException: Class testsms.TestSms can not access a member of class tables.Actor with modifiers "private"

可能我需要使用 Actor.class.getDeclaredMethods() 但我不知道如何。谁能帮我解决这个问题?

【问题讨论】:

    标签: java hibernate serialization field


    【解决方案1】:

    你可以试试f.setAccessible(true) 然后重新运行你的代码吗?

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 2019-08-03
      • 1970-01-01
      • 2019-07-29
      • 2023-02-17
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多