java反射机制的意思是说:在运行状态中,对于任何一个类,都知道它的属性和方法。对于任何一个对象,都能调用它的任何方法,这种动态获取的信息以及动态调用对象的方法的功能成为java的反射。
假设t是一个对象实体,Class ct = t.getClass()则是获取的该对象的类。
Field[] fields = ct.getDeclaredFields(); //获取该类的所有声明的成员变量,不包括父类中的成员变量
Method[] methods = ct.getDeclaredMethods(); //获取该类的所有声明的成员方法 ,不包括父类中的方法
getMethodName方法名如果是一个javaBean的话,可以根据前面获取的该类成员变量类型进行拼接。
if(field.getType()==boolean.class){
getMethodName = "is"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
for(Method method : methods){
if(method.getName().equals(getMethodName)){
isExist = true;
continue;
}
}
if(!isExist){
getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
}
}else{
getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
}
getMethodName假设为某类的方法名,调用invoke方法即可以执行该类的getMethodName方法,返回getMethodName方法的返回值。
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});