【solvebug】Java反射报错java.beans.IntrospectionException: Method not found,lombok的@Accessors注解

问题描述

Java反射报错java.beans.IntrospectionException: Method not found:setXXXX

问题分析及解决

1、getter/setter方法命名不规范,就是setXxx, setxxx这样的大小写;

2、实体类方法返回值问题
使用PropertyDescriptor descriptor = new PropertyDescriptor(fieldName, classz)时,要求 setter 返回值为 void,getter 返回值为属性类型,如下的getter方法返回的类型就不对,会报Method not found错误

    private Date startDate;

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    //将方法返回类型改成Date就解决了
    public String getStartDate() {
        return DateUtil.formatDate(startDate);
    }

3、实体类使用了lombok 中的 @Accessors(chain = true) 注解
该注解使得对象的 setter 方法返回对象本身,以便链式使用
new PropertyDescriptor(propertyName, clazz); 要求 setter 返回值为 void
解决:去掉 @Accessors(chain = true) 注解即可。或者在根据业务需求为需要反射的属性添加相应的getter/setter方法。

Demo反编译验证

使用lombok.Data

/**
 * <p>@Author: healker</p>
 * <p>@datetime: 2020/8/26 11:36</p>
 * <p>@description: </p>
 */
@Data
public class EntityDemo {
    private String testField;
    private List<EntityDemo> entityDemoList;

}

编译成class,再反编译后

使用lombok.Data,并添加@Accessors(chain = true)注解

/**
 * <p>@Author: healker</p>
 * <p>@datetime: 2020/8/26 11:36</p>
 * <p>@description: </p>
 */
@Data
@Accessors(chain = true)
public class EntityDemo {
    private String testField;
    private List<EntityDemo> entityDemoList;

}

编译成class,再反编译后testField,entityDemoList的setter方法都是返回实体本身(用以链式调用)。

使用lombok.Data,并添加@Accessors(chain = true)注解,手写testField字段的getter/setter方法

/**
 * <p>@Author: healker</p>
 * <p>@datetime: 2020/8/26 11:36</p>
 * <p>@description: </p>
 */
@Data
@Accessors(chain = true)
public class EntityDemo {
    private String testField;
    private List<EntityDemo> entityDemoList;

    public String getTestField() {
        return testField;
    }

    public void setTestField(String testField) {
        this.testField = testField;
    }
}

编译成class,再反编译后testField的setter方法返回void,entityDemoList的setter方法返回实体本身

原文地址:https://www.cnblogs.com/healkerzk/p/14254935.html