Java入门 - 10 反射 & 动态代理

反射 & 动态代理

前言

本文为B站Java教学视频BV1Kb411W75N的相关笔记,主要用于个人记录与分享,如有错误欢迎留言指出。
本章笔记涵盖视频内容P631~P665

1.反射概述

  • 动态语言:动态语言在运行时代码可以根据条件改变自身结构。Java本身是静态语言,但是通过反射机制可以获得一定的动态性
  • 反射(Reflection):反射是动态语言的关键,它允许程序在执行期间借助API获取任何类的内部信息,并能直接操作任意对象的内部属性及方法。加载完类之后,就产生了一个Class类型的对象,这个对象包含了对应类的结构信息,可以通过这个对象看到类的结构
  • 反射机制提供的功能:
    • 在运行时判断任意一个对象所属的类
    • 在运行时构造任意一个类的对象
    • 在运行时判断任意一个类所具有的成员变量和方法
    • 在运行时获取泛型信息
    • 在运行时调用任意一个对象的成员变量和方法
    • 在运行时处理注解
    • 生成动态代理
  • 注意:反射机制并没有破坏封装性,反射机制的加入只是将封装性由强制性变为建议性。在一般操作中,建议遵守封装性,但是在特殊情况下,可以通过反射强制调用类的内部方法/属性。

2.Class类

2.1 类的加载过程

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

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

public class Test{
    public static void main(String[] args) {
    }
    public void test3(){

        //方式一:调用运行时类的属性.class
        Class clazz1 = Person.class;
        System.out.println(clazz1);

        //方式二:通过运行时类的对象,调用getClass()
        Person p1 = new Person();
        Class clazz2 = p1.getClass();
        System.out.println(clazz2);
        
        try {
            
            //方式三:调用Class的静态方法:forName(String classPath)
            Class clazz3 = Class.forName("com.atguigu.java.Person");
            System.out.println(clazz3);

            //方式四:使用类的加载器:ClassLoader
            ClassLoader classLoader = Test.class.getClassLoader();
            Class clazz4 = classLoader.loadClass("com.atguigu.java.Person");
            System.out.println(clazz4);
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Person{
    
}

2.2 可以获取Class类的类型

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;

//只要元素类型和维度一样,就是同一个Class
int[] a = new int[10];
int[] b = new int[100];
Class c10 = a.getClass();
Class c11 = b.getClass();
//c10 == c11

2.3 创建运行时类的对象

public class Test{
    public static void main(String[] args) {

        Class<Person> clazz = Person.class;
        
        try {

            //newInstance():调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参的构造器
            Person obj = clazz.newInstance();   //泛型自动转换

            System.out.println(obj);
            
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

class Person{

}

3. 获取运行时类的结构

3.1 属性

public class Test{
    public static void main(String[] args) {
        Class 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);
        }
    }
}

class Person{
    
}

3.2 类的内部结构

public class Test{
    public static void main(String[] args) {
        Class clazz = Person.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        for(Field f : declaredFields){
            //1.权限修饰符
            int modifier = f.getModifiers();
            System.out.print(Modifier.toString(modifier)+ "\t");

            //2.数据类型
            Class type = f.getType();
            System.out.print(type.getName() + "\t");

            //3.变量名
            String fName = f.getName();
            System.out.print(fName);

            System.out.println();
        }
    }
}

class Person{
    
}

3.3 类的方法结构

public class Test{
    public static void main(String[] args) {
        Class clazz = Person.class;

        //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
        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);
        }
    }
}

class Person{

}

3.4 类的方法内部结构

/*
类方法的内部结构基本为:
@Xxx
权限修饰符 返回值类型 方法名(参数类型1 形参名1,....) throws XxxException{}
*/

public class Test{
    public static void main(String[] args) {
        Class 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.print(Modifier.toString(m.getModifiers()) + "\t");

            //3.返回值类型
            System.out.print(m.getReturnType().getName() + "\t");

            //4.方法名
            System.out.print(m.getName());
            System.out.print("(");

            //5.形参列表
            Class[] parameterTypes = m.getParameterTypes();
            if(!(parameterTypes == null && parameterTypes.length == 0)){
                for(int i = 0;i < parameterTypes.length;i++){
                    System.out.print(parameterTypes[i].getName() + "args_" + i);
                }
            }
            System.out.print(")");

            //6.抛出的异常
            Class[] exceptionTypes = m.getExceptionTypes();
            if(exceptionTypes.length > 0){
                System.out.print("throws ");
                for(int i = 0;i < exceptionTypes.length;i++){
                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }
            
            System.out.println();
        }
    }
}

class Person{

}

3.5 构造器结构

public class Othertest{
    public static void main(String[] args) {
        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 : constructors){
            System.out.println(c);
        }
    }
}

class Person{
    
}

3.6 父类及父类的泛型

public class Othertest{
    public static void main(String[] args) {
        Class clazz = Person.class;

        //获取运行时类的父类
        Class superclass = clazz.getSuperclass();
        System.out.println(superclass);

        //获取运行时类的带泛型的父类
        Type genericSuperclass = clazz.getGenericSuperclass();
        System.out.println(genericSuperclass);

        //获取运行时类的带泛型的父类的泛型
        Type genericSuperclass_ = clazz.getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) genericSuperclass_;
        
        //获取泛型类型
        Type[] actualTypeArguments = paramType.getActualTypeArguments();
        System.out.println(actualTypeArguments[0].getTypeName());
    }
}

class Person{

}

3.7 接口

public class Othertest{
    public static void main(String[] args) {
        Class clazz = Person.class;

        //1.获取运行时类实现的接口
        Class[] interfaces = clazz.getInterfaces();
        for(Class c : interfaces){
            System.out.println(c);
        }

        //2.获取运行时类的父类实现的接口
        Class[] interface1 = clazz.getSuperclass().getInterfaces();
        for(Class c : interface1){
            System.out.println(c);
        }
    }
}

class Person{

}

3.8 包

public class Othertest{
    public static void main(String[] args) {
        Class clazz = Person.class;

        Package pack = clazz.getPackage();
        System.out.println(pack);
    }
}

class Person{

}

3.9 注解

public class Othertest{
    public static void main(String[] args) {
        Class clazz = Person.class;

        Annotation[] annotations = clazz.getAnnotations();
        for(Annotation annos : annotations){
            System.out.println(annos);
        }
    }
}

class Person{

}

4. 调用/操作运行时类的结构

4.1 属性

public class FieldTest{
    public static void main(String[] args) {
        Class clazz = Person.class;

        try {

            //创建运行时类的对象
            Person p = (Person)clazz.newInstance();
            //1.getDeclaredField(String fieldName):获取运行时类中指定变量名的属性
            Field name = clazz.getDeclaredField("name");

            //2.保证当前属性是可访问的
            name.setAccessible(true);

            //3.获取,设置指定对象的此属性值
            //set():参数1:设置指定对象的属性 参数2:将此属性值设置为多少
            name.set(p,"Tom");
            //get():参数1:获取指定对象的当前属性值
            System.out.println(name.get(p));

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

class Person{

}

/*
如果只获取public权限的属性的话,可以使用Field id = clazz.getField("id");(不常使用)
这样获取的属性在get和set的时候不需要setAccessible(true)
*/

4.2 类中的方法结构

public class FieldTest{
    public static void main(String[] args) {
        Class clazz = Person.class;
        
        try {

            //创建运行时类的对象
            Person p = (Person)clazz.newInstance();

            //1.获取指定的某个方法
            //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"); //等价于String nation = p.show();
            System.out.println(returnValue);
            
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

class Person{
    
}

4.3 构造器

public class FieldTest{
    public static void main(String[] args) {
        Class clazz = Person.class;
        
        try {
            
            //1.获取指定的构造器
            //getDeclaredConstructor():参数:指明构造器的参数列表
            Constructor constructor = clazz.getDeclaredConstructor(String.class);

            //2.保证此构造器是可访问的
            constructor.setAccessible(true);

            //3.调用此构造器创建运行时类的对象
            Person per = (Person) constructor.newInstance("Tom");
            System.out.println(per);
            
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

class Person{

}

5. 动态代理

  • 定义:代理模式是指,使用一个代理将对象包装起来,然后用该代理对象取代原始对象。任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法调用转到原始对象上。

    静态代理的代理类和目标对象的类都是在编译期间定下来的,不利于程序的扩展,最好可以通过一个代理类完成全部的代理功能,所以就需要动态代理

    动态代理是指客户通过代理类来调用其它对象的方法,并且是在程序运行时根据需要动态创建目标类的代理对象。适用于调试和远程方法的调用,相比静态代理可以更加灵活和统一的处理众多的方法

5.1 静态代理

interface ClothFactory{
    void produceCloth();
}

//代理类
class ProxyClothFactory implements ClothFactory{
    
    private ClothFactory factory;	//用被代理类对象进行实例化
    
    public ProxyClothFactory(ClothFactory factory){
        this.factory = factory;
    }
    
    public void produceCloth(){
        System.out.println("代理工厂做了一些准备工作");
        
        factory.produceCloth();
        
        System.out.println("代理工厂做一些后续的收尾工作");
    }
}

//被代理类
class NikeClothFactory implements ClothFactory{
    
    public void produceCloth(){
        System.out.println("Nike工厂生产一批运动服");
    }
}

public class StaticProxyTest{
    public static void main(String[] args){
        //创建被代理类的对象
        ClothFactory nike = new NikeClothFactory();
        //创建代理类的对象
        ClothFactory proxyClothFactory  = new ProxyClothFactory(nike);
        
        proxyClothFactory.produceCloth();
    }
}

5.2 动态代理

interface Human{

    String getBelief();

    void eat(String food);
}

//被代理类
class SuperMan implements Human{

    public String getBelief(){
        return "I can fly";
    }

    public void eat(String food){
        System.out.println("");
    }
}

class ProxyFactory{
    //调用此方法,返回一个代理类的对象
    //obj:被代理类的对象
    public static Object getProxyInstance(Object obj){
        MyInvocationHandler handler = new MyInvocationHandler();

        handler.bind(obj);

        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
    }
}

class MyInvocationHandler implements InvocationHandler{

    private Object obj;//需要使用被代理类的对象进行赋值

    public void bind(Object obj){
        this.obj = obj;
    }

    //当通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()
    //当被代理类要执行的方法a的功能就声明在invoke()中
    public Object invoke(Object proxy,Method method,Object[] args) {

        //method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
        //obj:被代理类的对象
        Object returnValue = null;
        try {
            returnValue = method.invoke(obj,args);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //上述方法的返回值就作为当前类中的invoke()的返回值
        return returnValue;
    }
}


class ProxyTest{

    public static void main(String[] args){
        SuperMan superMan = new SuperMan();
        //proxyInstance:代理类的对象
        Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
        //当代理类对象调用方法时,会自动的调用被代理类中同名的方法
        System.out.println(proxyInstance.getBelief());
        proxyInstance.eat("FOOD");
    }
}
posted @   Solitary-Rhyme  阅读(65)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示