【问题标题】:Java Reflection: object is not an instance of declaring classJava反射:对象不是声明类的实例
【发布时间】:2021-09-18 03:24:53
【问题描述】:

用户类

public class User {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
        @Column(unique=true)
        private String username;
        @JsonIgnore
        private String password;
        private String firstName;
        private String lastName;
        private Date dob;
        private String motherName;
        private String fatherName;
        private String mobileNumber;
        @Column(unique=true)
        private String email;
        @ManyToOne
        @JoinColumn(name="role_id", nullable=false)
        private Role role;
        private String status;
    
        public void setPassword(String password) {
            this.password = PasswordEncoder.getEncodedPassword(password);
        }
    }

这是我的 UserRequest 类

@Data
public class UserRequest {
    private Long id;
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    private Date dob;
    private String motherName;
    private String fatherName;
    private String mobileNumber;
    private String email;
    private Long role;
    private String status;
}

我的复制方法存在于实用程序类中

public static void copy(Object dest, Object source) throws IntrospectionException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException {
    BeanInfo beanInfo = Introspector.getBeanInfo(source.getClass());
    PropertyDescriptor[] pdList = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor pd : pdList) {
        Method writeMethod = null;
        Method readMethod = null;
        try {
            writeMethod = pd.getWriteMethod();
            readMethod = pd.getReadMethod();
        } catch (Exception e) {
        }

        if (readMethod == null || writeMethod == null) {
            continue;
        }

        Object val = readMethod.invoke(source);
        writeMethod.invoke(dest, val);
    }
}

我将这个复制方法称为这样的

 Utility.copy(user,userRequest);

并在执行 writeMethod.invoke(dest, val) 时出现以下异常。有人可以帮忙吗?

object 不是声明类的实例 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native 方法)在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) 在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.base/java.lang.reflect.Method.invoke(Method.java:564)

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    您只获取 source 类的 BeanInfo,然后从该 BeanInfo 获取属性描述符...所以 writeMethod 上的设置器source 类,但您是在 destination 类的实例上调用它。

    您可能需要分别获取源类和目标类的BeanInfo,然后对于源中的每个属性,在目标类中找到具有相同名称(如果有)的属性,然后使用 属性的 write 方法来设置值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 2017-05-05
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多