今天做java的项目时
想通过反射为sql查询出的数据进行封装,结果一直报错
Exception in thread "main" java.beans.IntrospectionException: Method not found: isWBLDINST
at java.beans.PropertyDescriptor.<init>(Unknown Source)
at java.beans.PropertyDescriptor.<init>(Unknown Source)
at GetSet.testRef(GetSet.java:10)
at GetSet.main(GetSet.java:19)
但是我的WBLDINST用Eclipse自动生成了get和set方法
后来写个demo调试才发现原来是字段名大小写不一样导致的。
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class GetSet {
public static <T>void testRef(Class<T> clazz) throws Exception{
T obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields){
PropertyDescriptor descriptor = new PropertyDescriptor("WBLDINST", clazz);
Method method = descriptor.getWriteMethod();
System.out.println(method.getName());
method.invoke(obj, "12");
}
}
public static void main(String[] args) throws Exception {
// String s = "desc";
// System.out.println("set" + (s.toUpperCase().charAt(0)) + s.substring(1));
testRef(A.class);
}
}
class A {
private String name;
private String wbldInst;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWbldInst() {
return wbldInst;
}
public void setWbldInst(String wbldInst) {
this.wbldInst = wbldInst;
}
}