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

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

用户类

  1. public class User {
  2. @Id
  3. @GeneratedValue(strategy=GenerationType.AUTO)
  4. private Long id;
  5. @Column(unique=true)
  6. private String username;
  7. @JsonIgnore
  8. private String password;
  9. private String firstName;
  10. private String lastName;
  11. private Date dob;
  12. private String motherName;
  13. private String fatherName;
  14. private String mobileNumber;
  15. @Column(unique=true)
  16. private String email;
  17. @ManyToOne
  18. @JoinColumn(name="role_id", nullable=false)
  19. private Role role;
  20. private String status;
  21. public void setPassword(String password) {
  22. this.password = PasswordEncoder.getEncodedPassword(password);
  23. }
  24. }

这是我的userrequest类

  1. @Data
  2. public class UserRequest {
  3. private Long id;
  4. private String username;
  5. private String password;
  6. private String firstName;
  7. private String lastName;
  8. private Date dob;
  9. private String motherName;
  10. private String fatherName;
  11. private String mobileNumber;
  12. private String email;
  13. private Long role;
  14. private String status;
  15. }

我的复制方法出现在实用程序类中

  1. public static void copy(Object dest, Object source) throws IntrospectionException, IllegalArgumentException, IllegalAccessException,
  2. InvocationTargetException {
  3. BeanInfo beanInfo = Introspector.getBeanInfo(source.getClass());
  4. PropertyDescriptor[] pdList = beanInfo.getPropertyDescriptors();
  5. for (PropertyDescriptor pd : pdList) {
  6. Method writeMethod = null;
  7. Method readMethod = null;
  8. try {
  9. writeMethod = pd.getWriteMethod();
  10. readMethod = pd.getReadMethod();
  11. } catch (Exception e) {
  12. }
  13. if (readMethod == null || writeMethod == null) {
  14. continue;
  15. }
  16. Object val = readMethod.invoke(source);
  17. writeMethod.invoke(dest, val);
  18. }
  19. }

我把这个复制方法叫做这样的方法

  1. 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方法设置值。

相关问题