mercredi 7 juillet 2021

Java Reflection: object is not an instance of declaring class

User class

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);
        }
    }

Here is my UserRequest class

@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;
}

and my copy method is present in Utility class

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);
    }
}

and I'm calling this copy method something like this

 Utility.copy(user,userRequest);

and getting the following exception when writeMethod.invoke(dest, val) is executed. can anyone please help?

object is not an instance of declaring class at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564)





Aucun commentaire:

Enregistrer un commentaire