获取类属性的指定方法。
import lombok.Data;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Data
public class Comment {
private String id;
private String content;
private Date publishTime = new Date();
private String userId;
private String nickName;
private LocalDateTime createdateTime = LocalDateTime.now();
private Integer likeNum;
private Integer replayNum;
private String state;
private String parentId;
private String articleId;
//收集所有的属性的set方法
public static void main(String[] args) {
Map<String, Method> writeMethods = new ConcurrentHashMap<>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(Comment.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
//这里过滤掉系统属性:class
Arrays.stream(propertyDescriptors).filter(e -> e.getName() != "class").forEach(e -> writeMethods.put(e.getName(), e.getWriteMethod()));
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}