当用到一个类对象的时候,JVM会把此类的Class字节码文件加载到内存中(只加载一次),JVM会此类的信息封装成对象。利用封装好的对象获取类的相关信息进行构造类或者调用方法等,叫做反射。
反射的目的和作用就是为了开发者写出更通用的代码。
- 把类名称,继承,实现封装成Class对象
- 把类的构造方法封装成Constructor对象
- 把类的成员属性封装成File对象
- 把类的普通方法、返回值封装成Method对象
举例
package com.myjava.reflect;public class Person {private int _age;private String _name;public int get_age(){return _age;}public void say(){System.out.println(_name + "今年" + _age + "岁了");}public void set_age(int _age){this._age = _age;}public Person(int _age, String _name){super();this._age = _age;this._name = _name;}public String get_name(){return _name;}public void set_name(String _name){this._name = _name;} }
主程序
package com.myjava.reflect;import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException;/*** @ClassName: ReflectTest* @Description: TODO(这里用一句话描述这个类的作用)* @author 刘阳阳* @date 2016年10月5日 上午9:20:32**/public class ReflectTest {public static void main(String[] args)throws ClassNotFoundException, NoSuchMethodException,SecurityException, IllegalAccessException, IllegalArgumentException,InvocationTargetException, InstantiationException{// 根据类名进行加载,此加载不进行对象构造生成Class myClass = Class.forName("com.myjava.reflect.Person");// 这个需要导入对应的Person// Class myClass = Person.class;// 这个是进行实例化后获取对应的类信息// Class myClass = new Person(11, "honey").getClass();System.err.println(myClass.getName()); // 获取类名称Field[] Fields = myClass.getDeclaredFields();// 获取成员字段for (Field f : Fields){System.err.println(f.getName());// 获取成员名称System.err.println(f.getModifiers());// 声明的权限 default private public// protectedSystem.err.println(f.getType());// 获取成员类型 }Constructor[] constructors = myClass.getDeclaredConstructors();for (Constructor con : constructors){System.err.println(con.getName());System.err.println(con.getModifiers());// 声明的权限 default private// public protectedSystem.err.println(con.getParameterCount());// 参数个数System.err.println(con.getParameters()); // 参数集合 }// 调用此对象中的SAY方法,构造参数位_age=11,_name=honeymyClass.getMethod("say").invoke(myClass.getConstructor(int.class, String.class).newInstance(11, "honey"), null);}}
程序执行结果为
com.myjava.reflect.Person
_age
2
int
_name
2
class java.lang.String
com.myjava.reflect.Person
1
2
[Ljava.lang.reflect.Parameter;@15db9742
honey今年11岁了