Java笔记:反射

本文深入探讨了Java反射机制,包括其概念、功能、主要API以及在运行时操作类、对象的能力。通过示例展示了如何使用反射创建对象、访问私有结构,并对比了反射前后的类操作。此外,还讲解了类的加载、ClassLoader的工作原理以及动态代理的实现。反射为Java提供了强大的运行时代码操作能力,但也需要注意其对封装性的潜在影响。
摘要由CSDN通过智能技术生成

1. Java反射机制概述


1.1 说明

  • 反射机制允许程序在执行期间借助于反射提供的API获取任何类的内部信息,并能直接操作任意对象的内部属性和方法。
  • 在加载完类后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息,可以通过这个对象看到类的结构

1.2 功能

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

1.3 主要的API

  • java.lang.Class:代表一个类
  • java.lang.reflect.Method:代表类的方法
  • java.lang.reflect.Field:代表类的成员变量
  • java.lang.reflect.Constructor:代表类的构造器
  • ……

2. 理解Class类并获取Class实例(重点)


2.1 反射前后对于一个类操作的比较

反射之前,对于Person类的操作

public class Reflection01 {
    @Test
    public void test1() {
        //1. 创建Perdon类的对象
        Person p1 = new Person("费渡", 21);
        System.out.println(p1.toString());
        //2. 通过对象,调用其内部的属性、方法
        p1.age = 25;
        System.out.println(p1.toString());
        p1.show();
        //此时不可以通过Person类的对象调用其内部私有结构
    }
}

反射之后,对于Person类的操作

public class Reflection01 {
    @Test
    public void test2() throws Exception {
        Class personClass = Person.class;
        //1.通过反射创建Person类的对象
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        Person p = (Person) constructor.newInstance("简隋英", 30);
        System.out.println(p.toString());
        //2.通过反射,调用对象指定的属性、方法
        //2-1 调用对象的属性
        Field age = personClass.getDeclaredField("age");
        age.set(p, 20);
        System.out.println(p.toString());
        //2-2 调用对象的方法
        Method show = personClass.getDeclaredMethod("show");
        show.invoke(p);
        System.out.println("**************************************");
        //3.通过反射,可以调用Person类的私有结构
        //3-1 调用私有的构造器
        Constructor constructor1 = personClass.getDeclaredConstructor(String.class);
        constructor1.setAccessible(true);
        Person p1 = (Person) constructor1.newInstance("纪慎语");
        System.out.println(p1.toString());
        //3-2 调用私有的属性
        Field name = personClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(p1, "江停");
        System.out.println(p1.toString());
        //3-2 调用私有的方法
        Method showCouple = personClass.getDeclaredMethod("showCouple", String.class);
        showCouple.setAccessible(true);
        String couple = (String) showCouple.invoke(p1, "严峫");
        System.out.println(couple);
    }
}

2.2 反射与封装

封装性的访问权限控制是一种建议,反射提供了一种调用私有结构的方式

2.3 使用哪种方式调用公共结构

建议用直接new的方式
在不确定要new那个类的情况下,使用反射的方式(动态性),比如在JavaWeb书城项目中,解析URL后,通过反射确定要调用的方法

2.4 关于java.lang.Class类

程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class)。

接着使用java.exe命令对某个字节码文件进行解释运行,相当于将某个字节码文件加载到内存中,该过程称为类的加载。加载到内存中的类,被称为运行时类,该类即作为Class类的一个实例。换句话说,Class的实例就对应着一个运行时类。

加载到内存中的运行时类,会缓存一定的时间。在此时间之内,可以通过不同的方式来获取此运行时类。

2.5 获取Class实例的方式

public class Reflection01 {
    @Test
    public void test3() throws Exception {
        //方式一:调用运行时类的属性:.class
        Class personClass = Person.class;
        System.out.println(personClass);
        //方式二:通过运行时类的对象,调用 getClass 方法
        Person p = new Person();
        Class personClass1 = p.getClass();
        System.out.println(personClass1);
        //方式三:调用Class的静态方法:forName
        Class personClass2 = Class.forName("com.dudu.reflection.Person");
        System.out.println(personClass2);
        //方式四:使用类的加载器:ClassLoader
        ClassLoader classLoader = Reflection01.class.getClassLoader();
        Class personClass3 = classLoader.loadClass("com.dudu.reflection.Person");
        System.out.println(personClass3);
        
		//返回结果都为true
        System.out.println(personClass == personClass1);
        System.out.println(personClass == personClass2);
        System.out.println(personClass == personClass3);
    }
}

2.6 Class实例可以是哪些结构

public class Reflection01 {
    @Test
    public void test4() {
        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;//void
        Class c9 = Class.class;//Class本身也是一个类

        int[] a = new int[10];
        int[] b = new int[100];
        Class c10 = a.getClass();
        Class c11 = b.getClass();
        //返回true,只要数组的元素类型与维度一致,就是同一个Class实例
        System.out.println(c10 == c11);
    }
}

3. 类的加载与ClassLoader的理解


3.1 类的加载

当程序主动使用某个类时,如果该类还没有被加载到内存中,则系统会通过三个步骤来对该类进行初始化

  1. 类的加载:将类的class文件读入内存(java.exe命令),并为之创建一个Class对象,此过程由类加载器完成
  2. 类的链接:将类的二进制数据合并到JRE中
  3. 类的初始化:JVM负责对类进行初始化

3.2 类加载器

  • 作用
    将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆中生成一个代表这个类的Class对象,作为方法区中类数据的访问入口。
  • 类缓存
    标准的JavaSE类加载器可以按照要求查找类,但一旦某个类被加载到类加载器中,它将维持加载一段时间。不过JVM垃圾回收机制可以回收这些Class对象。
  • 演示
public class Reflection01 {
    @Test
    public void test5() {
        //对于自定义类,使用系统类加载器进行加载
        ClassLoader classLoader = Reflection01.class.getClassLoader();
        System.out.println(classLoader);
        //调用系统类加载器的 getParent 方法,获取扩展类加载器
        ClassLoader loaderParent = classLoader.getParent();
        System.out.println(loaderParent);
        //调用扩展类加载器的 getParent 方法,无法获取到引导类加载器
        //引导类加载器主要负责加载java的核心类库,无法加载自定义类
        ClassLoader loaderParentParent = loaderParent.getParent();
        System.out.println(loaderParentParent);
    }
}

3.3 读取配置文件

public class Reflection01 {
    @Test
    public void test6() throws Exception{
        Properties pros = new Properties();

        //读取配置文件的方式一:此时的文件路径默认在当前的工程下
        FileInputStream in = new FileInputStream("jdbc.properties");
        //读取配置文件的方式二:此时的文件路径默认在当前工程的src下
        ClassLoader classLoader = Reflection01.class.getClassLoader();
        InputStream in = classLoader.getResourceAsStream("jdbc1.properties");
        
        pros.load(in);
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        System.out.println(user + " : " + password);
    }
}

4. 创建运行时类的对象(重点)

newInstance():调用此方法,创建对应的运行时类的对象,内部调用了运行时类的无参构造器

public class Reflection01 {
    @Test
    public void test7() throws Exception {
        Class personClass = Class.forName("com.dudu.reflection.Person");
        Person p = (Person) personClass.newInstance();
        System.out.println(p);
    }
}

该方法正常执行的要求:
1.运行时类必须提供无参构造器
2.无参构造器的访问权限要满足要求(通常设置为public)

在JavaBean中要求提供一个public的无参构造器,原因:
1.便于通过反射创建运行时类对象
2.便于子类继承此运行时类默认调用super时,父类中存在该构造器

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


5.1 获取属性结构

getFields():获取当前运行时类及其父类中声明为public访问权限的属性

public class Demo {
	@Test
    public void t1() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Field[] fields = personClass.getFields();
    	for (Field field : fields) {
        	System.out.println(field);
    	}
 	}
}

getDeclaredFields():获取当前运行时类中声明的所有属性,不包含父类中声明的属性

public class Demo {
	@Test
    public void t2() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Field[] declaredFields = personClass.getDeclaredFields();
    	for (Field declaredField : declaredFields) {
        	System.out.println(declaredField);
    	}
 	}
}

获取属性的详细信息:权限修饰符,数据类型,变量名

public class Demo {
	@Test
    public void t3() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Field[] declaredFields = personClass.getDeclaredFields();
    	for (Field declaredField : declaredFields) {
        	System.out.println("权限修饰符:" + Modifier.toString(declaredField.getModifiers()));
        	System.out.println("数据类型:" + declaredField.getType());
        	System.out.println("变量名:" + declaredField.getName());
        	System.out.println("------------------------------------------");
    	}
 	}
}

5.2 获取方法结构

getMethods():获取当前运行时类及其父类中声明为public访问权限的方法

public class Demo {
	@Test
    public void t4() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Method[] methods = personClass.getMethods();
    	for (Method method : methods) {
    	    System.out.println(method);
    	}  
 	}
}

getDeclaredMethods():获取当前运行时类中声明的所有方法,不包含父类中声明的方法

public class Demo {
	@Test
    public void t5() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Method[] declaredMethods = personClass.getDeclaredMethods();
    	for (Method declaredMethod : declaredMethods) {
    	    System.out.println(declaredMethod);
    	}  
 	}
}

获取方法的详细信息:权限修饰符,返回值类型,方法名,参数列表,参数类型,异常,注解

public class Demo {
	@Test
    public void t6() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Method[] declaredMethods = personClass.getDeclaredMethods();
    	for (Method declaredMethod : declaredMethods) {
    	    System.out.println("注解:" + Arrays.toString(declaredMethod.getAnnotations()));
    	    System.out.println("权限修饰符:" + Modifier.toString(declaredMethod.getModifiers()));
    	    System.out.println("返回值类型:" + declaredMethod.getReturnType());
    	    System.out.println("方法名:" + declaredMethod.getName());
    	    System.out.println("参数列表:" + Arrays.toString(declaredMethod.getParameters()));
    	    System.out.println("参数类型:" + Arrays.toString(declaredMethod.getParameterTypes()));
    	    System.out.println("抛出的异常:" + Arrays.toString(declaredMethod.getExceptionTypes()));
    	    System.out.println("------------------");
    	}  
 	}
}

5.3 获取构造器结构

getConstructors():获取当前运行时类中声明为public访问权限的构造器

public class Demo {
	@Test
    public void t7() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Constructor[] constructors = personClass.getConstructors();
    	for (Constructor constructor : constructors) {
    		System.out.println(constructor);
 		}
 	}
}

getDeclaredConstructors():获取当前运行时类中声明的所有构造器

public class Demo {
	@Test
    public void t8() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Constructor[] declaredConstructors = personClass.getDeclaredConstructors();
    	for (Constructor declaredConstructor : declaredConstructors) {
    		System.out.println(declaredConstructor);
 		}
 	}
}

5.4 获取父类

获取运行时类的父类

public class Demo {
	@Test
    public void t9() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Class superclass = personClass.getSuperclass();
    	System.out.println(superclass);
 	}
}

获取运行时带泛型类的父类并获取泛型

public class Demo {
	@Test
    public void t10() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Type genericSuperclass = personClass.getGenericSuperclass();
    	System.out.println(genericSuperclass);

		ParameterizedType type = (ParameterizedType) genericSuperclass;
		Type[] arguments = type.getActualTypeArguments();
		//输出 java.lang.String
		System.out.println(arguments[0].getTypeName());
		System.out.println(((Class) arguments[0]).getName());
 	}
}

5.5 获取接口,包,注解等结构

获取运行时类实现的接口

public class Demo {
	@Test
    public void t11() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Class[] interfaces = personClass.getInterfaces();
    	System.out.println(Arrays.toString(interfaces));
 	}
}

获取运行时类所在的包

public class Demo {
	@Test
    public void t12() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Package classPackage = personClass.getPackage();
    	System.out.println(classPackage);
 	}
}

获取运行时类声明的注解

public class Demo {
	@Test
    public void t13() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Annotation[] annotations = personClass.getAnnotations();
    	System.out.println(Arrays.toString(annotations));
 	}
}

6. 调用运行时类的指定结构(重点)

调用运行时类的指定属性( getField() 方法只能获取到 public 权限的属性,并不常用)

public class Demo {
	@Test
    public void t1() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	Person person = (Person) personClass.newInstance();//获取对象
    	Field name = personClass.getDeclaredField("name");//获取name属性
    	name.setAccessible(true);//保证name属性可访问
    	//设置指定对象的属性值:参数1指明要设置的对象,参数2指定要设置的值
    	name.set(person, "dudu");
    	System.out.println(name.get(person));//获取指定对象的属性值
 	}
}

调用运行时类中的指定方法

public class Demo {
	@Test
	public void t() throws Exception {
		Class personClass = Class.forName("com.dudu.wen.Person");
		
		// ----- 调用静态方法 -----
		Method showDesc = personClass.getDeclaredMethod("showDesc");//获取静态方法
		showDesc.setAccessible(true);//保证当前方法可访问
		Object invoke = showDesc.invoke(personClass);
		showDesc.invoke(null);//静态方法属于类
		//invoke方法的返回值即为对应方法的返回值,对于没有返回值的方法invoke会返回 Null
		System.out.println(invoke);
		
		// ----- 调用非静态方法 -----
		Person person = (Person) personClass.newInstance();//获取对象,非静态方法要通过对象调用
		//获取方法:参数1指定要获取的方法名,参数2指明要获取的方法的形参列表
		Method method = personClass.getDeclaredMethod("show", String.class);
		method.setAccessible(true);
		//方法调用:参数1指定要调用该方法的对象,参数2为该方法需要传入的参数
		String nation = (String) method.invoke(person, "China");
		System.out.println(nation);
	}
}

调用运行时类中的指定构造器

public class Demo {
	@Test
    public void t() throws Exception {
    	Class personClass = Class.forName("com.dudu.wen.Person");
    	//获取构造器,需要指定构造器的参数类型
    	Constructor constructor = personClass.getDeclaredConstructor(String.class);
    	constructor.setAccessible(true);//保证构造器可访问
    	//使用构造器创建对象,需要传入参数值
    	Person dudu = (Person) constructor.newInstance("dudu");
    	System.out.println(dudu.toString());
 	}
}

7. 反射的应用:动态代理

  • 代理设计模式的原理:使用一个代理将对象包装起来,然后用该代理对象取代原始对象。任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法调用转到原始对象上。
  • 动态代理是指客户通过代理类来调用其他对象的方法,并且是在程序运行时根据需要动态创建目标类的代理对象
  • 动态代理相比于静态代理的优点:抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样可以更加灵活和统一的处理众多的方法

静态代理:代理类和被代理类在编译期间就确定下来

interface ClothesFactory {
    void produceClothes();
}

// 代理类
class ProxyClothesFactory implements ClothesFactory {
	private ClothesFactory factory;

    public ProxyClothesFactory(ClothesFactory factory) {
    	this.factory = factory;
    }

    @Override
    public void produceClothes() {
        System.out.println("代理工厂做一些准备工作");
        factory.produceClothes();
        System.out.println("代理工厂做一些后续的收尾工作");
    }
}

// 被代理类
class LiNingClothesFactory implements ClothesFactory{
	@Override
    public void produceClothes() {
    	System.out.println("李宁工厂生产一批运动服");
    }
}

public class StaticProxyTest {
    public static void main(String[] args) {
    	ClothesFactory clothesFactory = new LiNingClothesFactory();
    	ProxyClothesFactory proxyClothesFactory = new ProxyClothesFactory(clothesFactory);
    	proxyClothesFactory.produceClothes();
    }
}

动态代理

  • 如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象
  • 当通过代理类的对象调用方法时,如何动态的去调用被代理类中的同名方法
interface ClothesFactory {
    void produceClothes();
}

// 被代理类
class LiNingClothesFactory implements ClothesFactory{
	@Override
    public void produceClothes() {
    	System.out.println("李宁工厂生产一批运动服");
    }
}

class ProxyFactory {
	/**
     * 返回一个代理类的对象
     *
     * @param object 被代理类的对象
     * @return
     */
    public static Object getProxyInstance(Object object) {
    	MyInvocationHandler handler = new MyInvocationHandler();
    	handler.bind(object);
    	return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), handler);
    }
}

class MyInvocationHandler implements InvocationHandler {
	private Object obj;
	public void bind(Object obj) {
		this.obj = obj;
	}
	/**
     * 当通过代理类的对象调用方法时,就会自动地调用该方法
     *
     * @param proxy  代理类的对象
     * @param method 代理类对象要执行的方法
     * @param args   方法的参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    	return method.invoke(obj, args);
    }
}

public class ProxyTest {
    public static void main(String[] args) {
    	LiNingClothesFactory clothesFactory = new LiNingClothesFactory();
    	// 动态的获取代理类的对象
    	ClothesFactory proxy = (ClothesFactory) ProxyFactory.getProxyInstance(clothesFactory);
    	proxy.produceClothes();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值