java通过反射机制取javabean的属性值和方法
package com.landray.kmss.km.mdm.maindata.jdbc.tools;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Test {
public static void main(String[] args){
try {
TestBean bean = new TestBean();
String temp = "";
bean.setAge("20");
bean.setName("Shane");
bean.setSex("boy");
getClassInfo(bean);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getClassInfo(Object obj) throws Exception {
Class clas = Class.forName("com.landray.kmss.km.mdm.maindata.jdbc.tools.TestBean");
if(!(clas.isInstance(obj))){
System.out.println("传入的java实例与配置的java对象类型不符!");
return;
}
Field[] fields = clas.getDeclaredFields();
Method[] methods = clas.getDeclaredMethods();
System.out.println("--------------- 属性如下 -----------------");
for (Field field : fields) {
int mod = field.getModifiers();
System.out.println(Modifier.toString(mod) // 取得修饰符
+ " " + field.getType().getName() // 取得类型名
+ " " + field.getName()+ " " + field.get(obj)); // 取得属性名
}
System.out.println("--------------- 方法如下 -----------------");
for (Method method : methods) {
StringBuffer methodBuffer = new StringBuffer();
int mod = method.getModifiers();
methodBuffer.append(Modifier.toString(mod)) // 取得修饰符
.append(" ").append(method.getReturnType().getName()) // 取得返回值类型
.append(" ").append(method.getName()) // 取得方法名
.append("(");
for (Class ss : method.getParameterTypes()) {
methodBuffer.append(ss.getName()).append(","); // 取得参数
}
if(methodBuffer.lastIndexOf(",")>=0)
methodBuffer.deleteCharAt(methodBuffer.lastIndexOf(",")); // 去掉最后一个","
methodBuffer.append(")");
System.out.println(methodBuffer.toString()); // 打印输出
}
}
}