比较懒,就把练习的例子放上来了,注释就是对方法的解释
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectTest {
public interface China{
public String Region = null;
}
public static class Person implements China{
private String name;
private int age;
public Person(){
}
public Person(String name){
this.name = name;
}
public Person(int age){
this.age = age;
}
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
@Override
public String toString(){
return "["+this.name+" "+this.age+"]";
}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException,
SecurityException, NoSuchMethodException, NoSuchFieldException {
Person Person = new Person();
System.out.println(Person.getClass().getName());
Class PersonClass1 = null;
Class PersonClass2 = null;
Class PersonClass3 = null;
//三种方法创建Class 实例
PersonClass1 = Class.forName("ReflectTest$Person");
PersonClass2 = new Person().getClass();
PersonClass3 = Person.class;
Person per1 = (Person) PersonClass1.newInstance(); //若 Person 没有无参的构造器,会报InstantiationException,
per1.setName("candy");
per1.setAge(25);
System.out.println(per1);
//若类中就是没有无参的构造器,也可以使用这种方法
Constructor con[] = PersonClass1.getConstructors(); //con 数组的顺序与Person类中构造器编写的顺序一致
Person per2 = (ReflectTest.Person) con[0].newInstance();
Person per3 = (ReflectTest.Person) con[1].newInstance("alice");
Person per4 = (ReflectTest.Person) con[2].newInstance(27);
Person per5 = (ReflectTest.Person) con[3].newInstance("alice", 27);
//亦可以指定构造器
Person per6 = (ReflectTest.Person) PersonClass1.getConstructor(String.class).newInstance("lisa");
System.out.println(per6);
System.out.println(con[1].getParameterTypes()[0]); //得到方法参数
System.out.println(Modifier.toString(con[1].getModifiers()));//得到方法修饰符,如public
Method[] methods = PersonClass1.getMethods();
System.out.println(methods[0].getName()); //得到Person Class 的所有methods
Class<?> returnType=methods[0].getReturnType(); //方法的返回类型
Class<?> para[]=methods[0].getParameterTypes(); //方法的参数类型
Class<?> exce[]=methods[0].getExceptionTypes(); //方法的异常
Class inters[] = PersonClass1.getInterfaces(); //得到Person类实现的所有接口
System.out.println(PersonClass1.getSuperclass().getName());//继承的父类
Field[] fields = PersonClass1.getDeclaredFields(); //类的全部属性
Field[] inter_fields = PersonClass1.getFields(); //取得实现的接口或者父类的属性
// 通过反射调用方法
Method setAge = PersonClass1.getMethod("setAge", int.class);
setAge.invoke(PersonClass1.newInstance(), 26);
// 通过反射操作属性
Field nameField = PersonClass1.getDeclaredField("name");
nameField.setAccessible(true); //如何属性是private,没有这一步就没有权限set
nameField.set(PersonClass1.newInstance(), "cindy");
}
}