@SuppressWarnings("serial")
public class Bean implements Serializable {
public Integer x;
protected String y;
Date z;
private boolean k;
//
public static int getXX(){
return 1;
}
public void setX(int x,String y) {
this.x = x;
this.y = y;
}
//这上面两个不是setget方法
private boolean isK() {
return k;
}
private void setK(boolean k) {
this.k = k;
}
public Integer getX() {
return x;
}
public void setX(Integer x) {
this.x = x;
}
protected String getY() {
return y;
}
protected void setY(String y) {
this.y = y;
}
Date getZ() {
return z;
}
void setZ(Date z) {
this.z = z;
}
}
public static void main(String[] args) throws IntrospectionException,
NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
Bean bean = new Bean();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
if (descriptors != null) {//借用PropertyUtilsBean的写法
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
PropertyDescriptor descriptor = descriptors[i];
System.out.println("----------------" + name
+ "----------------");
System.out.println("read:");
System.out.println(MethodUtils.getAccessibleMethod(descriptor
.getReadMethod()));
System.out.println("write:");
System.out.println(MethodUtils.getAccessibleMethod(descriptor
.getWriteMethod()));
System.out.println("---------------------------------------");
}
}
Class[] classarr = { Integer.class, String.class };
System.out.println(MethodUtils.getAccessibleMethod(bean.getClass(),
"setX", Integer.class));
System.out.println(MethodUtils.getAccessibleMethod(bean.getClass(),
"setY", String.class));
System.out.println(MethodUtils.getAccessibleMethod(bean.getClass(),
"setZ", Date.class));
System.out.println(MethodUtils.getAccessibleMethod(bean.getClass(),
"setK", boolean.class));
System.out.println(MethodUtils.getAccessibleMethod(bean.getClass(),
"setX", classarr));
System.out.println(MethodUtils.getMatchingAccessibleMethod(bean
.getClass(), "setX", classarr));// getAccessibleMethod有什么区别?即便catch后也一样要求一一对应
System.out.println("*******************************");
MethodUtils.invokeExactMethod(bean, "setX", 1);// 如果x是int型怎么设值?
System.out.println(MethodUtils.invokeExactMethod(bean, "getX", null));
System.out.println(MethodUtils.invokeMethod(bean, "getX", null));// 和上面的区别是调用了getMatchingAccessibleMethod
System.out.println(MethodUtils.invokeStaticMethod(bean.getClass(),
"getXX", null));// 用于static
}
getAccessibleMethod是得到方法
invokeMethod是调用方法