一:Java反射机制概述
Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的信息,并能直接操作任意对象的内部属性及方法。
加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我可可以通过这个对象看到类的结构。这个对象就像一面镜子,透过镜子看到类的结构,所以,我们想象的称之为:反射。
二:理解Class类并获取Class实例(掌握)
(1)理解Class类
- 类的加载过程:程序经过javac.exe命令之后,会生成一个或多个字节码文件(.class结尾)。接着我们使用java.exe命令对某个字节码文件进行解释运行,相当于将某个字节码文件加载到内存中,此过程就称为类的加载。加载到内存中的类,我们称为运行时类,此运行时类,就作为Class的一个实例。
- 换句话说,Class的实例就对应着一个运行时类。
加载到内存中的运行时类,会缓存一定的时间,在此时间之内,我们可以通过不同的方式来获取此运行时类。
(2)获取Class实例
/*** 获取Class的实例的方式(前三种掌握,第四种了解)*/public class ReflectionTest1 {public static void main(String[] args) throws ClassNotFoundException {test4();}//方式一:调用运行时类的属性:.classpublic static void test1(){Class<Person> clazz = Person.class;System.out.println(clazz);//class cn.hgk.reflection.Person}//方式二:通过运行时类的对象,调用getClass()public static void test2(){Person p1 = new Person();Class<? extends Person> clazz = p1.getClass();System.out.println(clazz);//class cn.hgk.reflection.Person}//方式三:调用Class的静态方法:forName(String classPath)。(这种方式用的最多)public static void test3() throws ClassNotFoundException {Class clazz = Class.forName("cn.hgk.reflection.Person");//路径System.out.println(clazz);//class cn.hgk.reflection.Person}//方式四:使用类的加载器:ClassLoaderpublic static void test4() throws ClassNotFoundException {ClassLoader classLoader = ReflectionTest1.class.getClassLoader();Class clazz = classLoader.loadClass("cn.hgk.reflection.Person");System.out.println(clazz);//class cn.hgk.reflection.Person}}
三:类的加载与ClassLoader的理解
(1)类的加载
当程序主动使用某个类时,如果该类还未被加载到内存中,则系统会通过如下三个步骤来对该类进行初始化。
类的加载:将类的class文件读入内存,并为之创建一个java.lang.Class对象,此过程由类加载器完成。
- 类的链接:将类的二进制数据合并到JRE中。
-
(2)ClassLoader的理解
类加载器的作用:
类加载的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆内存中生成一个代表这个类的java.lang.Class对象,作为方法区中类数据的访问入口。
类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器中,他将维持加载(缓存)一段时间,不过JVM垃圾回收机制可以回收这些Class对象。
/*** 使用ClassLoader加载配置文件* Properties:用来读取配置文件*/public class Test1 {public static void main(String[] args) throws IOException {Properties pros = new Properties();//读取配置文件的方式一:FileInputStream fis = new FileInputStream("src\\jdbc.properties");//此时的文件默认在当前的module下pros.load(fis);String user = pros.getProperty("user");String password = pros.getProperty("password");System.out.println("user="+user+",password="+password);}}
四:创建运行时类的对象(掌握)
/*** 通过反射创建对应的运行时类的对象*/public class NewInstanceTest {public static void main(String[] args) throws IllegalAccessException, InstantiationException {Class<Person> clazz = Person.class;/*** newInstance():调用此方法创建运行时类的对象,* 其实newInstance()内部也调用了运行时类的空参构造器(只有通过构造器才能创建对象)* 要想此方法正常的长剑运行时类的对象,要求;* 1.运行时类必须提供空参的构造器* 2.空参的构造器的访问权限得够。通常,设置为public* 在javabean中要求提供一个public的空参构造器。原因:* 1.便于通过反射,创建运行时类的对象。* 2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器*/Person person = clazz.newInstance();System.out.println(person);}}
五:获取运行时类的完整结构
/*** 获取属性结构*/public static void test1(){Class<Person> clazz = Person.class;//方式一:getFields():获取当前运行类及其父类中声明为public访问权限的属性Field[] fields = clazz.getFields();for (Field f : fields) {System.out.println(f);}//方式二:getDeclaredFields():获取当前运行时类中声明的所有属性(不包含父类中的属性)Field[] declaredFields = clazz.getDeclaredFields();for (Field f : declaredFields) {System.out.println(f);}}/*** 获取运行时类的属性的内部结构*/public static void test2(){Class<Person> clazz = Person.class;Field[] declaredFields = clazz.getDeclaredFields();for (Field f : declaredFields) {//1.权限修饰符int modifiers = f.getModifiers();System.out.println(Modifier.toString(modifiers));//2.数据类型Class type = f.getType();System.out.println(type+"\t");//3.变量名String name = f.getName();System.out.println(name);}}/*** 获取运行时类的方法结构*/public static void test3(){Class<Person> clazz = Person.class;//getMethods():获取当前运行时类及其所有父类中声明为public权限的方法Method[] m = clazz.getMethods();for (Method method : m) {System.out.println(method);}//**********//getDeclaredMethods():获取当前运行时类中声明的所有方法(不包含父类中的方法)Method[] declaredMethods = clazz.getDeclaredMethods();for (Method d : declaredMethods) {System.out.println(d);}}/*** 获取运行时类的方法的内部结构** @Xxxx* 权限修饰符 返回值类型 方法名(参数类型1 形参名1,...) throws XxxException{}*/public static void test4(){Class<Person> clazz = Person.class;Method[] declaredMethods = clazz.getDeclaredMethods();for (Method m : declaredMethods) {//1.获取方法声明的注解Annotation[] annos = m.getAnnotations();for (Annotation a : annos) {System.out.println(a);}//2.权限修饰符System.out.println(Modifier.toString(m.getModifiers())+"\t");//3.返回值类型System.out.println(m.getReturnType().getName()+"\t");//4.方法名System.out.println(m.getName());//5.形参System.out.println("(");Class[] parameterTypes = m.getParameterTypes();System.out.println(")");}}
六:调用运行时类的指定结构(掌握)
(1)属性
/*** 调用运行时类中指定的结构(属性、方法、构造器)*///1.属性(方式一):getField()。(不需要掌握)public static void test5() throws Exception {Class<Person> clazz = Person.class;//创建运行时类的对象Person p = clazz.newInstance();//方法一:获取指定的属性(要求运行时类中属性的权限是public的)(因此通常不用这个方法)Field id = clazz.getField("id");/*** 设置当前属性的值*set():* 参数一:指明设置哪个对象的属性* 参数二:将此属性设置为多少*/id.set(p,1001);/*** 获取当前属性的值*set():* 参数一:指明获取哪个对象的属性*/int o = (int)id.get(p);System.out.println(o);//1001}//1.属性(方式二)(不需要掌握)public static void test6() throws Exception {Class<Person> clazz = Person.class;//创建运行时类的对象Person p = clazz.newInstance();//getDeclaredField("name"):获取运行时类指定变量名的属性Field name = clazz.getDeclaredField("name");//只有完成这个name.setAccessible(true);操作才可以修改权限为private的属性name.setAccessible(true);//保证当前属性是可访问的name.set(p,"hgk");String o = (String)name.get(p);System.out.println(o);}
(2)方法
//2.方法(需要掌握)public static void test7() throws Exception {Class<Person> clazz = Person.class;//创建运行时类的对象Person p = clazz.newInstance();/*** 1.获取指定的某个方法* getDeclaredMethod():* 参数一:指明获取的方法的名称* 参数二:指明获取的方法的形参列表*/Method show = clazz.getDeclaredMethod("show", String.class);show.setAccessible(true);/*** invoke():* 参数一:方法的调用者* 参数二:给方法形参赋值的实参.* invoke()的返回值即为对应类中调用的方法的返回值*/String chn = (String) show.invoke(p, "CHN");System.out.println(chn);//******如何调用静态方法***********public static void info()Method info = clazz.getDeclaredMethod("info");show.setAccessible(true);//如果调用的运行时类中的方法没有返回值,则此invoke()返回nullObject invoke = info.invoke(Person.class);System.out.println(invoke);//null}
(3)构造器
//3.构造器(不需要掌握)public static void test8() throws Exception {Class<Person> clazz = Person.class;/*1.获取指定的构造器*/Constructor<Person> constructor = clazz.getDeclaredConstructor(String.class);//2.保证此构造器是可访问的constructor.setAccessible(true);//3.调用此构造器创建运行时类的对象Person person = constructor.newInstance("hgk");System.out.println(person.toString());//Person{name='hgk', age=0, id=0}}
