package wangChaoPA实习工作练习.com.反射;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflect
{
// 获取到某个反射类中的所有的方法
public static Method[] getMethods(Class ownerClass)
{
// 只获取该类中所有访问权限的方法(不包含的父类当中的方法)
Method[] methods = ownerClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++)
{
System.out.println(methods[i]);
}
return methods;
}
// 获取到某个反射类中的所有的属性
public static Field[] getProperty(Class ownerClass)
{
// ownerClass.getFields();只获取public访问权限的字段(包含父类中的字段)
// 只获取该类中所有访问权限的字段(不包含的父类当中的字段)
Field[] fields = ownerClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++)
{
System.out.println(fields[i]);
}
return fields;
}
// 获取反射类的某个public属性值
public static Object getProperty(Object owner, String fieldName)
throws Exception
{
// 获取到对象的所属类
Class ownerClass = owner.getClass();
// 获取到该类的某个属性
Field field = ownerClass.getField(fieldName);
// 获取到某个对象的特定属性
Object property = field.get(owner);
System.out.println(fieldName + "的属性值:" + property.toString());
return property;
}
// 执行反射类中某个方法
public static Object invokeMethod(Object owner, String methodName,
Object[] agrs) throws Exception
{
Class ownerClass = owner.getClass();
Method method = ownerClass.getMethod(methodName, null);
Object result = method.invoke(owner, agrs);
System.out.println(result);
return result;
}
public static void main(String[] args) throws Exception
{
Class modelClass = Class.forName("wangChaoPA实习工作练习.com.反射.Model");
Object classObj = modelClass.newInstance();
getProperty(modelClass);
getMethods(modelClass);
invokeMethod(classObj, "getAccount", null);
getProperty(classObj, "age");
}
}