博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA进阶学习笔记(8):反射
阅读量:2159 次
发布时间:2019-05-01

本文共 14965 字,大约阅读时间需要 49 分钟。

目录

1. 概述

1.1 反射的概念

Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。

加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射。
在这里插入图片描述

1.2 应用

在运行时判断任意一个对象所属的类

在运行时构造任意一个类的对象
在运行时判断任意一个类所具有的成员变量和方法
在运行时获取泛型信息
在运行时调用任意一个对象的成员变量和方法
在运行时处理注解
生成动态代理

1.3 反射的例子

Person.java:

package com.wzc.java;public class Person {
private String name; public int age; public String getName() {
return name; } public void setName(String name) {
this.name = name; } public int getAge() {
return age; } public void setAge(int age) {
this.age = age; } public Person() {
} private Person(String name) {
this.name = name; } public Person(String name, int age) {
this.name = name; this.age = age; } @Override public String toString() {
return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } public void show(){
System.out.println("你好,我是一个人"); } private String showNation(String nation){
System.out.println("我的国籍是" + nation); return nation; }}
//反射之前,对于Person的操作    @Test    public void test1(){
//1.创建Person类的对象 Person p1 = new Person("Tom",12); //2.通过对象调用其中的属性和方法 p1.age = 10; System.out.println(p1.toString()); p1.show(); //在Person类外部,不可以通过Person类的对象调用其内部私有结构 //比如:name、showNation()以及私有构造器 } //有了反射之后,对Person的操作 @Test public void test2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class clazz = Person.class; //1.通过反射创建Person类的对象 Constructor cons = clazz.getConstructor(String.class, int.class); Object obj = cons.newInstance("Tom", 12); Person p = (Person)obj; System.out.println(p.toString()); //2.通过反射调用对象指定属性方法 //调用属性 Field age = clazz.getDeclaredField("age"); age.set(p,10); System.out.println(p.toString()); //调用方法 Method show = clazz.getDeclaredMethod("show"); show.invoke(p); System.out.println("*************************************"); //通过反射可以调用Person类的私有结构。比如:私有构造器、方法、属性 Constructor cons1 = clazz.getDeclaredConstructor(String.class); cons1.setAccessible(true); Person p1 = (Person)cons1.newInstance("Jerry"); System.out.println(p1); //调用私有属性 Field name = clazz.getDeclaredField("name"); name.setAccessible(true); name.set(p1,"LaoLiu"); System.out.println(p1); //调用私有方法 Method showNation = clazz.getDeclaredMethod("showNation", String.class); showNation.setAccessible(true); String nation = (String)showNation.invoke(p1,"中国");//相当于 String nation = p1.showNation("中国") System.out.println(nation); }

2. 理解Class类并获取Class的实例

2.1 Class类的理解

1.类的加载过程: 程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾)。接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此运行时类,就作为Class的一个实例。

2.换句话说,Class的实例就对应着一个运行时类。
3.加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式来获取此运行时类。

2.2 获取Class实例的方式

@Test    public void test3() throws ClassNotFoundException {
//方式一:调用运行时类的属性:.class Class clazz1 = Person.class; System.out.println(clazz1); //方式二:通过运行时类的对象,调用getClass() Person p1 = new Person(); Class clazz2 = p1.getClass(); System.out.println(clazz2); //方式三:调用Class的静态方法:forname(Striing classPath) Class clazz3 = Class.forName("com.wzc.java.Person"); System.out.println(clazz3); System.out.println(clazz1 == clazz2); //true 都指向同一个地址对应同一个class System.out.println(clazz2 == clazz3); //true //方式四:使用类的加载器 ClassLoader classLoader = ReflectionTest.class.getClassLoader(); Class clazz4 = classLoader.loadClass("com.wzc.java.Person"); System.out.println(clazz4); System.out.println(clazz4 == clazz1); //true }

有Class对象的一些类型:

(1)class:外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
(2)interface:接口
(3)[]:数组
(4)enum:枚举
(5)annotation:注解@interface
(6)primitive type:基本数据类型
(7)void

Class c1 = Object.class;Class c2 = Comparable.class;Class c3 = String[].class;Class c4 = int[][].class;Class c5 = ElementType.class;Class c6 = Override.class;Class c7 = int.class;Class c8 = void.class;Class c9 = Class.class;int[] a = new int[10];int[] b = new int[100];Class c10 = a.getClass();Class c11 = b.getClass();// 只要数组元素类型与维度一样,就是同一个ClassSystem.out.println(c10 == c11); //true

3. 类的加载过程与ClassLoader

3.1 类的加载过程

在这里插入图片描述

在这里插入图片描述
类加载器的作用:
类加载:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆中生成一个代表这个类java.lang.Class对象,作为方法区中类数据的访问入口。
类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器中,它将维持加载(缓存)一段时间。不过JVM垃圾回收机制可以回收这些Class对象。

3.2 ClassLoader理解

类加载器作用是用来把类(class)装载进内存的。JVM 规范定义了如下类型的类的加载器。

在这里插入图片描述
了解类的加载器:

@Test    public void test1(){
//对于自定义类,使用系统类加载器进行加载 ClassLoader classLoader = ClassLoadertest.class.getClassLoader(); System.out.println(classLoader); //系统加载器 //调用系统类加载器的getParent():获取扩展类加载器 ClassLoader classLoader1 = classLoader.getParent(); System.out.println(classLoader1);//扩展类加载器 //调用扩展器加载器类的getParent():无法获取引导类加载器 //引导类加载器主要负责加载java的核心类库,无法加载自定义类 ClassLoader classLoader2 = classLoader1.getParent(); System.out.println(classLoader2);//null 不代表没有,而是无法获取 引导类加载器 ClassLoader classLoader3 = String.class.getClassLoader(); System.out.println(classLoader3); //null 引导类加载器 }

3.3 使用加载器加载文件

如加载JDBC文件(两种方式):

@Test    public void test2() throws Exception {
Properties pros = new Properties(); //此时的文件默认在当前module下 //读取配置文件的方式一:// FileInputStream fis = new FileInputStream("jdbc.properties");// FileInputStream fis = new FileInputStream("src\\jdbc1.properties");// pros.load(fis); //读取配置文件的方式二:使用classloader //配置文件默认识别为:当前module的src下 ClassLoader classLoader = ClassLoadertest.class.getClassLoader(); InputStream is = classLoader.getResourceAsStream("jdbc1.properties"); pros.load(is); String user = pros.getProperty("username"); String password = pros.getProperty("password"); System.out.println("user = " + user + ",password = " + password); }

4. 创建运行时类的对象

4.1 通过反射获取运行时类的对象

@Test    public void test1() throws IllegalAccessException, InstantiationException {
Class
clazz = Person.class; /*newInstance():调用此方法,创建对应的运行时类的对象。内部调用了类的空参构造器 要想使用此方法创建运行时类的对象,要求: 1.运行时必须提供空参构造器 2.空参的构造器的访问权限得够。通常为public 在javabean中要求提供一个public的空参构造器 1.便于通过反射,创建运行时类的对象 2.便于子类继承此运行类时,默认调用super()时,保证父类有此构造器 */ Person obj = clazz.newInstance(); //该方法在java9之后已经过时 System.out.println(obj); }

4.2 体会反射的动态性

java是一种动态语言,在运行时可以根据某些条件改变自身结构,比如根据一些判断语句,创建对象也不可能总是一样的。反射机制可以在这种动态语言下创建出对应的类。

//体会反射的动态性    @Test    public void test2(){
for (int i = 0; i < 100; i++) {
int num = new Random().nextInt(3); // 0,1,2 String classPath = ""; switch (num){
case 0: classPath = "java.util.Date"; break; case 1: classPath = "java.lang.Object"; break; case 2: classPath = "com.wzc.java.Person"; break; } try {
Object instance = getInstance(classPath); System.out.println(instance); } catch (Exception e) {
e.printStackTrace(); } } } //创建一个指定类的对象,classpath:指定类的全类名 public Object getInstance(String classPath) throws Exception {
Class Clazz = Class.forName(classPath); return Clazz.newInstance(); }

5. 获取运行时类的完整结构

5.1 获取当前类的属性结构

@Test    public void test1(){
Class clazz = Person.class; //获取属性结构 //getFields():获取当前运行时类及父类中声明为public访问权限的属性 Field[] fields = clazz.getFields(); for (Field f : fields) {
System.out.println(f); } System.out.println(); //getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性) Field[] declaredFields = clazz.getDeclaredFields(); for (Field f : declaredFields) {
System.out.println(f); } } @Test public void test3(){
Class clazz = Person.class; Field[] declaredFields = clazz.getDeclaredFields(); for(Field f:declaredFields){
//1.权限修饰符 int modifier = f.getModifiers(); System.out.print(Modifier.toString(modifier) + ", "); //2.数据类型 Class type = f.getType(); System.out.print(type.getName() + ", "); //3.变量名 String fName = f.getName(); System.out.print(fName); System.out.println(); } }

5.2 获取当前类的方法结构

@Test    public void test1(){
Class clazz = Person.class; //getMethods():获取当前运行时类及其所有父类中声明为publi权限的方法 Method[] methods = clazz.getMethods(); for(Method m:methods){
System.out.println(m); } System.out.println(); //getDeclaredMethods():获取当前运行时类中声明的所有方法。(不含父类中声明的) Method[] declaredMethods = clazz.getDeclaredMethods(); for(Method m: declaredMethods){
System.out.println(m); } } //@Xxxx //权限修饰符 返回值类型 方法名(参数类型1 形参名1 ...)throws XxxException() @Test public void test2(){
Class clazz = Person.class; Method[] declaredMethods = clazz.getDeclaredMethods(); for(Method m : declaredMethods){
//1.获取方法声明的注解 Annotation[] annos = m.getAnnotations(); for(Annotation a : annos){
System.out.print(a); } //2.权限修饰符 System.out.print(Modifier.toString(m.getModifiers()) + ", "); //3.返回值类型 System.out.print(m.getReturnType().getName() + ", "); //4.方法名 System.out.print(m.getName()); //5.形参列表 System.out.print("("); Class[] parameterTypes = m.getParameterTypes(); if(!(parameterTypes == null && parameterTypes.length == 0)){
for(int i=0; i
0){
System.out.print("throws "); for (int i=0; i

5.3 获取当前类的构造器

@Test    public void test1(){
Class clazz = Person.class; //getConstructors():获取当前运行时类中声明为public的构造器 Constructor[] constructors = clazz.getConstructors(); for(Constructor c : constructors){
System.out.println(c); } System.out.println(); //getDeclaredConstructors():获取当前运行类中声明的所有的构造器 Constructor[] declaredConstructors = clazz.getDeclaredConstructors(); for(Constructor c : declaredConstructors){
System.out.println(c); } }

5.4 获取当前类的父类及泛型

//获取运行时的父类    @Test    public void test2(){
Class clazz = Person.class; Class superclass = clazz.getSuperclass(); System.out.println(superclass); } //获取运行带泛型的父类 @Test public void test3(){
Class clazz = Person.class; Type genericSuperclass = clazz.getGenericSuperclass(); System.out.println(genericSuperclass); } //获取运行带泛型的父类的泛型 @Test public void test4(){
Class clazz = Person.class; Type genericSuperclass = clazz.getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) genericSuperclass; //获取泛型类型 Type[] actualTypeArguments = paramType.getActualTypeArguments(); System.out.println(actualTypeArguments[0]); System.out.println(((Class)actualTypeArguments[0]).getName()); }

5.4 获取当前类的接口、包、声明的注解

//获取运行时类实现的接口    @Test    public void test5(){
Class clazz = Person.class; Class[] interfaces = clazz.getInterfaces(); for(Class c : interfaces){
System.out.println(c); } System.out.println(); //获取运行时父类的接口 Class[] interfaces1 = clazz.getSuperclass().getInterfaces(); for(Class c : interfaces1){
System.out.println(c); } } //获取运行时类所在的包 @Test public void test6(){
Class clazz = Person.class; Package aPackage = clazz.getPackage(); System.out.println(aPackage); } //获取运行时类声明的注解 @Test public void test7(){
Class clazz = Person.class; Annotation[] annotations = clazz.getAnnotations(); for(Annotation annos : annotations){
System.out.println(annos); } }

6. 获取运行时类的指定结构

6.1 获取运行时类的指定属性

//No    @Test    public void testFiled() throws Exception {
Class clazz = Person.class; //创建运行时类的对象 Person p = (Person) clazz.newInstance(); //获取指定的属性:要求运行时类中属性声明为public //通常不采用此方法 Field id = clazz.getField("id"); //设置当前属性的值 //set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少 id.set(p,1001); //获取当前属性的值 //get():参数1:获取哪个对象的当前属性值 int pId = (int) id.get(p); System.out.println(pId); } //Yes //操作运行时类中的指定属性 @Test public void test2() throws Exception {
Class clazz = Person.class; //创建运行时类的对象 Person p = (Person)clazz.newInstance(); //1. getDeclaredField(String fieldName):获取运行时类中指定变量名的属性 Field name = clazz.getDeclaredField("name"); //2.保证当前属性是可访问的 name.setAccessible(true); //3.获取、设置指定对象的此属性值 name.set(p, "Tom"); System.out.println(name.get(p)); }

6.2 获取运行时类的指定方法

//Yes    //操作运行时类中的指定方法    @Test    public void test3() throws Exception {
Class clazz = Person.class; //创建运行时的对象 Person p = (Person)clazz.newInstance(); //获取指定的某个方法 //getDeclaredMethod():参数1 :指明获取的方法的名称 参数2:指明获取的方法的形参列表 Method show = clazz.getDeclaredMethod("show", String.class); //2.保证当前方法是可访问的 show.setAccessible(true); //3. 调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参 //invoke()的返回值即为对应类中调用的方法的返回值。 Object returnValue = show.invoke(p, "CHN"); System.out.println(returnValue); System.out.println("***************如何调用静态方法**************"); Method showDesc = clazz.getDeclaredMethod("showDesc"); showDesc.setAccessible(true); //Object returnVal = showDesc.invoke(null); //已经加载了Person类 Object returnVal = showDesc.invoke(Person.class); System.out.println(returnVal); }

6.3 获取运行时类的指定构造器

//调用运行时类中的指定构造器    @Test    public void testConstructor() throws Exception{
Class clazz = Person.class; Constructor constructor = clazz.getDeclaredConstructor(String.class); constructor.setAccessible(true); Person per = (Person) constructor.newInstance("Tom"); System.out.println(per); }

参考资料:

[1]尚硅谷宋康红java基础教程

转载地址:http://hkgwb.baihongyu.com/

你可能感兴趣的文章
Leetcode C++ 《第181场周赛-2》 1390. 四因数
查看>>
阿里云《云原生》公开课笔记 第一章 云原生启蒙
查看>>
阿里云《云原生》公开课笔记 第二章 容器基本概念
查看>>
阿里云《云原生》公开课笔记 第三章 kubernetes核心概念
查看>>
阿里云《云原生》公开课笔记 第四章 理解Pod和容器设计模式
查看>>
阿里云《云原生》公开课笔记 第五章 应用编排与管理
查看>>
阿里云《云原生》公开课笔记 第六章 应用编排与管理:Deployment
查看>>
阿里云《云原生》公开课笔记 第七章 应用编排与管理:Job和DaemonSet
查看>>
阿里云《云原生》公开课笔记 第八章 应用配置管理
查看>>
阿里云《云原生》公开课笔记 第九章 应用存储和持久化数据卷:核心知识
查看>>
linux系统 阿里云源
查看>>
国内外helm源记录
查看>>
牛客网题目1:最大数
查看>>
散落人间知识点记录one
查看>>
Leetcode C++ 随手刷 547.朋友圈
查看>>
手抄笔记:深入理解linux内核-1
查看>>
内存堆与栈
查看>>
Leetcode C++《每日一题》20200621 124.二叉树的最大路径和
查看>>
Leetcode C++《每日一题》20200622 面试题 16.18. 模式匹配
查看>>
Leetcode C++《每日一题》20200625 139. 单词拆分
查看>>