用法见源码注释:
/**
* Java 反射 Demo
*/
public class ReflectTest {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
/**
* 获取类对象的成员变量的方式
*/
* Class clazz = Person.class;
* Object object = clazz.newInstance();
* System.out.println(object);
// 获取类对象所有public修饰的成员变量
Field[] fields = clazz.getFields();
for (Field field: fields) {
System.out.println(field.getName() + ":" +field.get(object));
}
// 获取类对象指定名词的public成员变量
* Field field = clazz.getField("name");
// 动态改变public成员变量的值
field.set(object, "haha");
System.out.println("改变name字段值后:"+ object);
// 获取类对象指定名词的声明成员变量(包含private类型的变量)
Field field2 = clazz.getDeclaredField("id");
System.out.println(field2);
// 动态改变private类型成员变量id的值
field2.setAccessible(true);
field2.set(object,"123456");
System.out.println(object);
/**
* 获取类对象成员方法的方式
*/
Class<Person> clazz = Person.class;
Object obj = clazz.newInstance();
// 获取类对象所有的public类型的方法(不含父类的)
Method [] methods = clazz.getDeclaredMethods();
System.out.println("输出方法:");
for(Method method : methods) {
System.out.println(method);
}
Method m1 = clazz.getMethod("show"); m1.invoke(obj);
Method m2 = clazz.getMethod("show", int.class);
m2.invoke(obj, 23);
Method m3 = clazz.getDeclaredMethod("show", String.class);
m3.setAccessible(true); m3.invoke(obj, "hello world");
}
/** 获取类对象的三种方式 */
private void getClassObject() {
// 第一种方式
Person p1 = new Person();
Class cz1 = p1.getClass();
System.out.println("第一种:" + cz1);
// 第二种方式
Class<Person> cz2 = Person.class;
System.out.println("第二种:" + cz2);
// 第三种方式
try {
Class cz3 = Class.forName("com.test.demo.Person");
System.out.println("第三种:" + cz3);
System.out.println("cz1 == cz2 ?:" + (cz1 == cz2));
System.out.println("cz2 == cz3 ?:" + (cz2 == cz3));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取类对象构造方法的方式
*
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void getConstructor(Class cz2) throws NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// 获取Person类对象所有公共的构造方法
Constructor[] constor = cz2.getConstructors();
for (Constructor con : constor) {
System.out.println(con);
}
// 获取Person类对象无参数的构造方法
Constructor ctor1 = cz2.getConstructor();
Object ob1 = ctor1.newInstance();
// 获取Person类对象指定参数类型的构造方法
Constructor ctor2 = cz2.getConstructor(int.class, int.class, String.class);
Object ob2 = ctor2.newInstance(1, 2, "hello world");
// 获取Person类对象声明的指定参数的构造方法(可获取私有方法)
Constructor ctor3 = cz2.getDeclaredConstructor(int.class);
// 将私有的(private)转为公有的的(public),为了在外部访问私有变量或私有方法
ctor3.setAccessible(true);
Object ob3 = ctor3.newInstance(3);
cz2.newInstance();
}
}
网友评论