gpt4 book ai didi

java - 是否可以使用 getter/setter 方法映射成员?

转载 作者:行者123 更新时间:2023-11-30 09:14:38 24 4
gpt4 key购买 nike

比如我有一些类有几个字段,其中一个如下,我想输出它实例的所有字段,但是我必须用getter方法得到成员名之间的映射,我能得到吗通过反射(reflection)?

public class MappingMemberWithGetterOrSetter {
private String memberOne;
private int memberTwo;

public String getMemberOne() {
return memberOne;
}

public void setMemberOne(String memberOne) {
this.memberOne = memberOne;
}

public int getMemberTwo() {
return memberTwo;
}

public void setMemberTwo(int memberTwo) {
this.memberTwo = memberTwo;
}
}

最佳答案

也许这就是您想要的。随着Introspector你可以获得BeanInfo这使您可以访问 bean 的 PropertyDescriptors .

BeanInfo beanInfo = Introspector.getBeanInfo(MappingMemberWithGetterOrSetter.class, Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyName = propertyDescriptor.getName();
Method getter = propertyDescriptor.getReadMethod();
Method setter = propertyDescriptor.getWriteMethod();
Field field = MappingMemberWithGetterOrSetter.class
.getDeclaredField(propertyName);
System.out.println("Property " + propertyName + " field: " + field);
System.out.println("Getter " + getter);
System.out.println("Setter " + setter);
}

关于java - 是否可以使用 getter/setter 方法映射成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20353966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com