Java反射机制

Java -- 浅入Java反射机制
http://www.cnblogs.com/wjtaigwh/p/6640748.html

API中给我们提供了一下方法

getName():获得类的完整名字。
getFields():获得类的public类型的属性。
getDeclaredFields():获得类的所有属性。
getMethods():获得类的public类型的方法。
getDeclaredMethods():获得类的所有方法。
getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。
getConstructors():获得类的public类型的构造方法。
getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
newInstance():通过类的不带参数的构造方法创建这个类的一个对象。


获取类中全部属性

Class<?> clazz = Class.forName("com.qianmo.flowlayout.reflection.User");
//获取本类中的全部属性
Field[] field = clazz.getDeclaredFields();
for (int i = 0; i < field.length; i++) {
//权限修饰符
String priv = Modifier.toString(field[i].getModifiers());
//属性类型
Class<?> type = field[i].getType();
System.out.println("修饰符:" + priv + ",属性类型:" + type.getName());

}
//获取实现的接口或者父类的属性
Field[] fild1 = clazz.getFields();

for (int i = 0; i <fild1.length ; i++) {
int mo = fild1[i].getModifiers();
String priv = Modifier.toString(mo);
// 属性类型
Class<?> type = fild1[i].getType();
System.out.println(priv + " " + type.getName() + " " + fild1[i].getName() + ";");
}
获取类中的全部方法
Class<?> clazz = Class.forName("com.qianmo.flowlayout.reflection.User");
Method method[] = clazz.getMethods();
for (int i = 0; i < method.length; i++) {
Class<?> returnType = method[i].getReturnType();
Class<?> para[] = method[i].getParameterTypes();
int temp = method[i].getModifiers();
System.out.println(method[i].getName() + "," + returnType.getName() + "," + Modifier.toString(temp));
for (int j = 0; j < para.length; j++) {
System.out.print(para[j].getName());
}
}


通过反射调用类中的方法

Class<?> clazz = Class.forName("com.qianmo.flowlayout.reflection.User");
Method method = clazz.getMethod("getAge");

method.invoke(clazz.newInstance());

method = clazz.getMethod("setAge", int.class);
method.invoke(clazz.newInstance(), 20);

通过反射操作类中的属性(包括私有属性)

Class<?> clazz = Class.forName("com.qianmo.flowlayout.reflection.User");
User user = (User) clazz.newInstance();
Field field = clazz.getDeclaredField("age");
field.setAccessible(true);
field.set(user, 50);
System.out.print(field.get(user));

原文地址:https://www.cnblogs.com/bluestorm/p/9448955.html