java反射:对象不是声明类的示例

zrfyljdw  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(419)

用户类

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)时获取以下异常。有人能帮忙吗?
对象不是java.base/jdk.internal.reflect.nativemethodaccessorimpl.invoke0(本机方法)处java.base/jdk.internal.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:64)处java.base/jdk.internal.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)处java.invoke处声明类的示例java.base/java.lang.reflect.method.invoke(method.java:564)

4si2a6ki

4si2a6ki1#

你只得到了 BeanInfo 对于源类,然后从中获取属性描述符 BeanInfo ... 所以 writeMethod 是源类上的setter,但您在目标类的示例上调用它。
你可能需要得到 BeanInfo 分别针对源类和目标类,然后针对源中的每个属性,在目标类中找到具有相同名称(如果有)的属性,并使用该属性的write方法设置值。

相关问题