天天看點

JAVA30天-進階篇-7-反射Java反射機制概述了解Class類并擷取Class執行個體類的加載與ClassLoader的了解建立運作時類的對象擷取運作時類的完整結構-了解調用運作時類的指定結構-掌握反射的應用:動态代理

Java反射機制概述

概念

JAVA30天-進階篇-7-反射Java反射機制概述了解Class類并擷取Class執行個體類的加載與ClassLoader的了解建立運作時類的對象擷取運作時類的完整結構-了解調用運作時類的指定結構-掌握反射的應用:動态代理

反射相關的主要API

* java.lang.Class:代表一個類
* java.lang.reflect.Method:代表類的方法
* java.lang.reflect.Field:代表類的成員變量
* java.lang.reflect.Constructor:代表類的構造器
           

基本使用

// 反射操作
    @Test
    public void test1() throws Exception {
        Class clas = Person.class; // 禁止class作為變量名

        //1.通過反射,建立Person類的對象
        Constructor constructor = clas.getConstructor(String.class, int.class);
        Object obj = constructor.newInstance("Tom", 12);
        Person person = (Person)obj;
        System.out.println(person); // Person{name='Tom', age=12}

        //2.通過反射,調用對象指定的屬性、方法
        // 調用屬性
        Field age = clas.getDeclaredField("age");
        age.set(person,30);
        System.out.println(person); // Person{name='Tom', age=30}
        // 調用方法
        Method show = clas.getDeclaredMethod("show");
        show.invoke(person); // 你好,xxxx

        System.out.println("*******************************");

        //通過反射,可以調用Person類的私有結構的。比如:私有的構造器、方法、屬性
        //調用私有的構造器
        Constructor constructor1 = clas.getDeclaredConstructor(String.class);
        constructor1.setAccessible(true);
        Object obj1 = constructor1.newInstance("jack");
        Person person1 = (Person)obj1;
        System.out.println(person1); // Person{name='jack', age=0}
        //調用私有的屬性
        Field name = clas.getDeclaredField("name");
        name.setAccessible(true);
        name.set(person1,"jacklove");
        System.out.println(person1); // Person{name='jacklove', age=0}
        //調用私有的方法
        Method showNation = clas.getDeclaredMethod("showNation", String.class);
        showNation.setAccessible(true);
        showNation.invoke(person1,"中華"); // 我的國籍是:中華

    }
           

了解Class類并擷取Class執行個體

關于java.lang.Class類的了解

* 類的加載過程:
    程式經過javac.exe指令以後,會生成一個或多個位元組碼檔案(.class結尾)。
    接着我們使用java.exe指令對某個位元組碼檔案進行解釋運作。相當于将某個位元組碼檔案加載到記憶體中。
    此過程就稱為類的加載。加載到記憶體中的類,我們就稱為運作時類,此運作時類,就作為Class的一個執行個體。
    
* 換句話說,Class的執行個體就對應着一個運作時類。
* 加載到記憶體中的運作時類,會緩存一定的時間。在此時間之内,我們可以通過不同的方式來擷取此運作時類。
* Class類是Reflection的根源,針對任何你想動态加載、運作的類,唯有先獲得相應的Class對象
           

擷取Class類的執行個體(四種方法)

//擷取Class的執行個體的方式(前三種方式需要掌握)
    @Test
    public void test3() throws ClassNotFoundException {
        //方式一:調用運作時類的屬性:.class
        Class clas1 = Person.class;
        
        //方式二:通過運作時類的對象,調用getClass()
        Class clas2 = (new Person()).getClass();

        //方式三:調用Class的靜态方法:forName(String classPath)
        Class<?> clas3 = Class.forName("reflection_zgc.Person");

        //方式四:使用類的加載器:ClassLoader  (了解)
        ClassLoader classLoader = Person.class.getClassLoader();
        Class clas4 = classLoader.loadClass("reflection_zgc.Person");

        System.out.println(clas1); // class reflection_zgc.Person
        System.out.println(clas1 == clas2); // true
        System.out.println(clas1 == clas3); // true
        System.out.println(clas1 == clas4); // true
    }
           

類的加載與ClassLoader的了解

目錄:https://blog.csdn.net/admin741admin/article/details/109146291

具體:https://blog.csdn.net/admin741admin/article/details/107944341

使用ClassLoader加載配置檔案

@Test
    public void test1() throws IOException {
        //讀取配置檔案的方式一:
        //此時的檔案預設在目前的module下。
//        Properties properties =  new Properties();
//        FileInputStream fis = new FileInputStream("jdbc1.properties");
//        properties.load(fis);


//        //讀取配置檔案的方式二:使用ClassLoader
        //配置檔案預設識别為:目前module的src下
        Properties properties =  new Properties();
        ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("jdbc1.properties");
        properties.load(resourceAsStream);

        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        System.out.println("user = " + user + ",password = " + password);
    }
           

中文亂碼

JAVA30天-進階篇-7-反射Java反射機制概述了解Class類并擷取Class執行個體類的加載與ClassLoader的了解建立運作時類的對象擷取運作時類的完整結構-了解調用運作時類的指定結構-掌握反射的應用:動态代理

建立運作時類的對象

無參構造

/*
        newInstance():調用此方法,建立對應的運作時類的對象。内部調用了運作時類的空參的構造器。

        要想此方法正常的建立運作時類的對象,要求:
        1.運作時類必須提供空參的構造器
        2.空參的構造器的通路權限得夠。通常,設定為public。


        在javabean中要求提供一個public的空參構造器。原因:
        1.便于通過反射,建立運作時類的對象
        2.便于子類繼承此運作時類時,預設調用super()時,保證父類有此構造器

         */
        Class<Person> clazz = Person.class;
        Person obj = clazz.newInstance();
        System.out.println(obj);

           

有參構造

//1.根據全類名擷取對應的Class對象
String name = “atguigu.java.Person";
Class clazz = null;
clazz = Class.forName(name);
//2.調用指定參數結構的構造器,生成Constructor的執行個體
Constructor con = clazz.getConstructor(String.class,Integer.class);
//3.通過Constructor的執行個體建立對應類的對象,并初始化類屬性
Person p2 = (Person) con.newInstance("Peter",20);
System.out.println(p2);
           

擷取運作時類的完整結構-了解

/*
    擷取構造器結構

     */
    @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);
        }

    }

    /*
    擷取運作時類的父類

     */
    @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);
    }

    /*
    擷取運作時類的帶泛型的父類的泛型


    代碼:邏輯性代碼  vs 功能性代碼
     */
    @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].getTypeName());
        System.out.println(((Class)actualTypeArguments[0]).getName());
    }

    /*
    擷取運作時類實作的接口
     */
    @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 pack = clazz.getPackage();
        System.out.println(pack);
    }

    /*
        擷取運作時類聲明的注解

     */
    @Test
    public void test7(){
        Class clazz = Person.class;

        Annotation[] annotations = clazz.getAnnotations();
        for(Annotation annos : annotations){
            System.out.println(annos);
        }
    }
           
/**
     * 擷取運作時類的方法結構
     */
    @Test
    public void test1(){

        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);
        }
    }

    /*
    @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.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++){

                    if(i == parameterTypes.length - 1){
                        System.out.print(parameterTypes[i].getName() + " args_" + i);
                        break;
                    }

                    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++){
                    if(i == exceptionTypes.length - 1){
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }

                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }


            System.out.println();
        }



    }
           
/**
     * 擷取目前運作時類的屬性結構
     */
    @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 test2(){
        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();
        }


    }
           

調用運作時類的指定結構-掌握

getField和getDeclaredField差別:前者要求運作時類中屬性聲明為public,後者沒限制

setAccessible,保證目前屬性/方法/構造器是可通路的,一般用于配合getDeclaredxxx使用

/*

        不需要掌握
     */
    @Test
    public void testField() 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);


    }
    /*
    如何操作運作時類中的指定的屬性 -- 需要掌握
     */
    @Test
    public void testField1() 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));
    }

    /*
    如何操作運作時類中的指定的方法 -- 需要掌握
     */
    @Test
    public void testMethod() throws Exception {

        Class clazz = Person.class;

        //建立運作時類的對象
        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("CHN");
        System.out.println(returnValue);

        System.out.println("*************如何調用靜态方法*****************");

        // private static void showDesc()

        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        //如果調用的運作時類中的方法沒有傳回值,則此invoke()傳回null
//        Object returnVal = showDesc.invoke(null);
        Object returnVal = showDesc.invoke(Person.class);
        System.out.println(returnVal);//null

    }

    /*
    如何調用運作時類中的指定的構造器
     */
    @Test
    public void testConstructor() throws Exception {
        Class clazz = Person.class;

        //private Person(String name)
        /*
        1.擷取指定的構造器
        getDeclaredConstructor():參數:指明構造器的參數清單
         */

        Constructor constructor = clazz.getDeclaredConstructor(String.class);

        //2.保證此構造器是可通路的
        constructor.setAccessible(true);

        //3.調用此構造器建立運作時類的對象
        Person per = (Person) constructor.newInstance("Tom");
        System.out.println(per);

    }
           

反射的應用:動态代理

靜态代理舉例

// 統一接口
interface ClothFactory{
    void produceCloth();
}

//代理類
class ProxyClothFactory implements ClothFactory{
    private ClothFactory clothFactory;

    public ProxyClothFactory(ClothFactory clothFactory){
        this.clothFactory = clothFactory;
    }

    @Override
    public void produceCloth() {
        System.out.println("代理做的事情1");
        this.clothFactory.produceCloth();
        System.out.println("代理做的事情2");
    }
}

// 被代理類
class NikeClothFactory implements ClothFactory{

    @Override
    public void produceCloth() {
        System.out.println("nike的産品");
    }
}

public class StaticProxyTest {
    public static void main(String[] args) {
        ClothFactory clothFactory  = new NikeClothFactory();
        ProxyClothFactory proxyClothFactory = new ProxyClothFactory(clothFactory);
        proxyClothFactory.produceCloth();
        // 代理做的事情1
        //nike的産品
        //代理做的事情2
    }
}
           

動态代理舉例+AOP

// 統一接口
interface Human{

    String getBelief();

    void eat(String food);
}

//被代理類
class SuperMan implements Human{

    @Override
    public String getBelief() {
        return "SuperMan的getBelief方法調用";
    }

    @Override
    public void eat(String food) {
        System.out.println("我在吃" + food);
    }
}

// 生成代理對象1
class ProxyFactory{
    // 調用此方法,傳回一個代理類的對象。
    public static Object getProxyInstance(Object object) {
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
        myInvocationHandler.bind(object);
        // ClassLoader loader, Class<?>[] interfaces, InvocationHandler h
        return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),myInvocationHandler);
    }
}

// 生成對象2
class MyInvocationHandler implements InvocationHandler{
    private Object obj;
    public void bind(Object obj){
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Aop
        AopUtil aopUtil = new AopUtil();
        aopUtil.method1();

        // method:即為代理類對象調用的方法,此方法也就作為了被代理類對象要調用的方法
        // obj:被代理類的對象
        Object invoke = method.invoke(this.obj, args);

        aopUtil.method2();
        return invoke;
    }
}


class AopUtil{

    public void method1(){
        System.out.println("====================通用方法一====================");

    }

    public void method2(){
        System.out.println("====================通用方法二====================");
    }

}

public class ProxyTest {
    public static void main(String[] args) {
        SuperMan superMan = new SuperMan();
        // 生成代理對象
        Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);

        String belief = proxyInstance.getBelief();
        System.out.println(belief);
        proxyInstance.eat("龍蝦");


        System.out.println("**********************************");
        NikeClothFactory nikeClothFactory = new NikeClothFactory();
        ClothFactory proxyInstance1 = (ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory);
        proxyInstance1.produceCloth();
    
        // ====================通用方法一====================
        //====================通用方法二====================
        //SuperMan的getBelief方法調用
        //====================通用方法一====================
        //我在吃龍蝦
        //====================通用方法二====================
        //**********************************
        //====================通用方法一====================
        //nike的産品
        //====================通用方法二====================
    }
}