什么是反射?
即通过字节码文件对象去使用成员。
(1)获取字节码文件对象的三种方式:
A:Object类的getClass()方法
B:数据类型的静态class属性
C:Class类的静态方法forName()
得到字节码文件对象后,我们可以通过这个对象获取类的构造方法,并创建对象,使用它的成员方法和成员变量。
举例:构造方法的遍历和调用
public class ConstructorTest {
/**
* @param args
* @throws ClassNotFoundException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
Class<?> a = Class.forName("com.day17.constructor.Animal");
Constructor<?>[] con = a.getConstructors(); //获取公开的构造方法
for (Constructor<?> co : con) {
System.out.println(co); //public com.day17.constructor.Animal()
}
System.out.println("-------------");
Constructor<?>[] con2 = a.getDeclaredConstructors(); //获取所有的构造方法
for (Constructor<?> co : con2) {
System.out.println(co); //com.day17.constructor.Animal(java.lang.String,int,java.lang.String)
//public com.day17.constructor.Animal()
}
System.out.println("-------------");
Constructor<Animal> dcon = (Constructor<Animal>) a.getDeclaredConstructor(String.class,int.class,String.class);
dcon.setAccessible(true);
Animal ni = dcon.newInstance("小狗",20,"白色");
System.out.println(ni);
}
}
举例:成员方法的遍历和调用(成员变量同理)
public class MethodTest {
/**
* @param args
* @throws ClassNotFoundException
* @throws Exception
* @throws NoSuchMethodException
*/
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, Exception {
// TODO Auto-generated method stub
Class<?> c = Class.forName("com.day17.method.Animal");
Constructor<?> con = c.getConstructor();
Object ni = con.newInstance();
Method[] dm = c.getDeclaredMethods();
for (Method method : dm) {
System.out.println(method);
}
System.out.println("-----------------");
Method dme = c.getDeclaredMethod("eat");
System.out.println(dme);
dme.invoke(ni);
Method dmf = c.getDeclaredMethod("fun");
dmf.setAccessible(true);
dmf.invoke(ni);
}
}