java - 从具有对象 "Field"的私有(private)字段获取值。 java

标签 java hibernate serialization field

我的问题是,我想使用 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() 但我不知道如何使用。谁能帮我解决这个问题吗?

最佳答案

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

关于java - 从具有对象 "Field"的私有(private)字段获取值。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8111658/

相关文章:

wcf - 数据合约中未设置数据成员字段时如何不返回 null

Java 无法使用有效的 SSL 证书

java - iMacros for loop POS={{k}} k 不持有整数值/存储问题

java - 线程上下文中的 String 对象和 StringBuffer 对象有什么区别?

java - 使用 Hibernate 时出现 ORA-02292

java - Spring Security 身份验证失败 : error org. hibernate.HibernateException:未找到当前线程的 session

ios - 如何在应用程序 session 之间维护对象?

java - 无法安装 python javabridge

java - 使用 Hibernate 查找给定 Java 类型的特定数据库类型

java - 我们可以序列化 java 套接字对象以通过 Kafka 队列发送吗