一、定义:JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
sun为我们提供了那些反射机制中的类:
java.lang.Class;
java.lang.reflect.Constructor;
java.lang.reflect.Field;
java.lang.reflect.Method;
java.lang.reflect.Modifier;
二、Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。
1、获取Class对象有三种方式
//第一种方式: Class cls = Class.forName("com.sample.pojo.Student"); //第二种方式: //java中每个类型都有class 属性. Class cls = Student.class; //第三种方式: //java语言中任何一个java对象都有getClass 方法 Student s = new Student(); Class cls = s.getClass(); //cls是运行时类 (s的运行时类是Student)
2、 创建对象:获取类以后我们来创建它的对象,利用newInstance():
//创建此Class 对象所表示的类的一个新实例 Object obj = cls.newInstance(); //调用了Student的无参数构造方法.
3、获取类的属性、方法、构造器
//返回一个权限为public的指定属性为name的 Field 对象 Field field=cls.getField("name") ; //返回一个指定属性为name的 Field 对象 Field field=cls.getDeclaredField("name") ; // 返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有public字段。 Field[] fields=cls.getFields() ; // 返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段。 Field[] fields=cls.getDeclaredFields() ;
Method getMethod(String name, Class<?>... parameterTypes)
返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
Method[] getMethods()
返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的public 方法。
Method getDeclaredMethod(String name, Class<?>... parameterTypes)
返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。
Method[] getDeclaredMethods()
返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。
T newInstance()
创建此 Class 对象所表示的类的一个新实例。 <new Instance()可以动态的创建对象>
String toString()
将对象转换为字符串。
// 通过反射调用方法 // 首先需要获得与该方法对应的Method对象 Method addMethod = classType.getMethod("add", new Class[] { int.class,int.class }); // 第一个参数是方法名,第二个参数是这个方法所需要的参数的Class对象的数组 // 调用目标方法 Object result = addMethod.invoke(invokeTester, new Object[] { 1, 2 }); System.out.println(result); // 此时result是Integer类型
Constructor con = c.getConstructor(); //没有执行构造, Object cObj = c.getConstructor().newInstance();//调用无参的构造方法 Constructor conAll = c.getConstructor(int.class,String.class,int.class); Object caobj = conAll.newInstance(1001,"zjamgs",234235);//调用含参的构造方法.