69期-Java SE-024-反射-2-001-002

 

### 反射應用

經過反射機制調用方法

```java
package com.southwind.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.southwind.entity.Student;

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("張三");
        student.show();
        
        Class clazz = student.getClass();
        try {
            Method method = clazz.getMethod("setId", Long.class);
            method.invoke(student, 2L);
            method = clazz.getMethod("setName", String.class);
            method.invoke(student, "李四");
            method = clazz.getMethod("show", null);
            method.invoke(student, null);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
```



經過反射機制訪問成員變量

```java
package com.southwind.test;

import java.lang.reflect.Field;

import com.southwind.entity.Student;

public class Test2 {
    public static void main(String[] args) {
        Class clazz = Student.class;
        //獲取目標類自己以及父類的全部public成員變量
//        Field[] fields = clazz.getFields();
//        for(Field field:fields) {
//            System.out.println(field);
//        }
//        System.out.println("********************");
        Student student = new Student();
        student.setId(1L);
        student.setName("張三");
        //獲取目標類自己的所有成員變量
        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields) {
//            try {
//                System.out.println(field.get(student));
//            } catch (IllegalArgumentException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
            field.setAccessible(true);
            if(field.getName().equals("id")) {
                try {
                    field.set(student, 2L);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else {
                try {
                    field.set(student, "李四");
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            try {
                System.out.println(field.get(student));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("成員變量名稱:"+field.getName());
            System.out.println("成員變量數據類型:"+field.getType().getName());
            System.out.println("訪問權限:"+getModifiers(field.getModifiers()));
        }
        
        System.out.println(student.getId());
        System.out.println(student.getName());
//        System.out.println("*********************");
//        try {
//            Field field = clazz.getField("id");
//            System.out.println(field);
//        } catch (NoSuchFieldException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (SecurityException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        System.out.println("************************");
//        try {
//            Field field = clazz.getDeclaredField("id");
//            System.out.println(field);
//        } catch (NoSuchFieldException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (SecurityException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
    
    public static String getModifiers(int modifier) {
        String result = "";
        switch(modifier) {
        case 0:
            result = "";
            break;
        case 1:
            result = "public";
            break;
        case 2:
            result = "private";
            break;
        case 3:
            result = "protected";
            break;
        }
        return result;
    }
}
```



經過反射機制調用構造函數

```java
package com.southwind.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.southwind.entity.Student;

public class Test3 {
    public static void main(String[] args) {
        Class clazz = Student.class;
        Constructor<Student> constructor = null;
        try {
//            constructor = clazz.getConstructor(null);
            constructor = clazz.getConstructor(Long.class,String.class);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        System.out.println(constructor);
        try {
            Student student = constructor.newInstance(3L,"小明");
            System.out.println(student);
            Student student1 = new Student();
            System.out.println(student1);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
```



### 動態代理

代理模式,它是一種經常使用的 Java 設計模式,指的是軟件設計所遵循的一套理論和準則。

在處理某個業務邏輯時,經過代理的方式來完成。

委託方、代理方

委託方和代理方有一個共性,即雙方都具有完成需求的能力。

Java中將對象所具有的能力封裝成接口,委託方和代理方須要實現同一個接口。

代理對象能夠爲委託對象進行消息預處理,過濾消息以及過後處理消息等。

代理類和委託類之間存在注入的關聯關係。

咱們在訪問委託對象時,是經過代理對象來間接訪問的,代理模式就是經過這種間接訪問的方式,爲程序預留出可處理的空間,利用此空間,在不影響核心業務的基礎上能夠附加其餘的業務,這就是代理模式的優點。



代理模式又能夠分爲靜態代理和動態代理,二者的區別在於靜態代理須要預先編寫好代理類的代碼,在編譯期間代理類的 class 文件就已經生成了。

靜態代理就是預先寫好代理類,動態代理是程序運行期間動態地生成代理類。

People.javajava

package com.southwind.entity;

public class People {
    public int age;
}

 

Student.java設計模式

package com.southwind.entity;

public class Student extends People {
    private Long id;
    private String name;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public void show() {
        System.out.println("學生信息");
        System.out.println("ID:"+this.id);
        System.out.println("姓名:"+this.name);
    }
    public Student(Long id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public Student() {
        super();
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }    
    
}

Apple.javaide

package com.southwind.proxy;

public class Apple implements Phone {

    @Override
    public String salePhone() {
        // TODO Auto-generated method stub
        return "銷售iPhone手機";
    }

}

 

Benz.java函數

package com.southwind.proxy;

public class Benz implements Car {

    @Override
    public String saleCar() {
        // TODO Auto-generated method stub
        return "銷售奔馳汽車";
    }

}

 

BMW.javathis

package com.southwind.proxy;

public class BMW implements Car {

    @Override
    public String saleCar() {
        // TODO Auto-generated method stub
        return "銷售寶馬汽車";
    }

}

 

Car.javaspa

package com.southwind.proxy;

public interface Car {
    public String saleCar();
}

 

CarProxy.java設計

package com.southwind.proxy;

public class CarProxy implements Car {
    private Car car;
    public CarProxy(Car car) {
        // TODO Auto-generated constructor stub
        this.car = car;
    }

    @Override
    public String saleCar() {
        // TODO Auto-generated method stub
        return this.car.saleCar();
    }

}

 

Huawei.java代理

package com.southwind.proxy;

public class HuaWei implements Phone {

    @Override
    public String salePhone() {
        // TODO Auto-generated method stub
        return "銷售華爲手機";
    }

}

 

MyProxy.javacode

package com.southwind.proxy;

public class MyProxy implements Car,Phone{
    private Object obj;
    
    public MyProxy(Object obj) {
        // TODO Auto-generated constructor stub
        this.obj = obj;
    }

    @Override
    public String salePhone() {
        // TODO Auto-generated method stub
        Phone phone = (Phone) obj;
        return phone.salePhone();
    }

    @Override
    public String saleCar() {
        // TODO Auto-generated method stub
        Car car = (Car) obj;
        return car.saleCar();
    }
}

 

Phone.java對象

package com.southwind.proxy;

public interface Phone {
    public String salePhone();
}

 

PhoneProxy.java

package com.southwind.proxy;

public class PhoneProxy implements Phone {
    private Phone phone;
    
    public PhoneProxy(Phone phone) {
        this.phone = phone;
    }
    
    @Override
    public String salePhone() {
        // TODO Auto-generated method stub
        System.out.println("代理模式");
        return this.phone.salePhone();
    }
    
}

 

Test.java

package com.southwind.proxy;

public class Test {
    public static void main(String[] args) {
        Phone phone = new Apple();
        System.out.println(phone.salePhone());
        phone = new HuaWei();
        System.out.println(phone.salePhone());
    }
}

 

Test2.java

package com.southwind.proxy;

public class Test2 {
    public static void main(String[] args) {
        Phone phone = new Apple();
        PhoneProxy proxy = new PhoneProxy(phone);
        System.out.println(proxy.salePhone());
        phone = new HuaWei();
        proxy = new PhoneProxy(phone);
        System.out.println(proxy.salePhone());
    }
}

Test.java

package com.southwind.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.southwind.entity.Student;

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("張三");
        student.show();
        
        Class clazz = student.getClass();
        try {
            Method method = clazz.getMethod("setId", Long.class);
            method.invoke(student, 2L);
            method = clazz.getMethod("setName", String.class);
            method.invoke(student, "李四");
            method = clazz.getMethod("show", null);
            method.invoke(student, null);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

Test2.java

package com.southwind.test;

import java.lang.reflect.Field;

import com.southwind.entity.Student;

public class Test2 {
    public static void main(String[] args) {
        Class clazz = Student.class;
        //獲取目標類自己以及父類的全部public成員變量
//        Field[] fields = clazz.getFields();
//        for(Field field:fields) {
//            System.out.println(field);
//        }
//        System.out.println("********************");
        Student student = new Student();
        student.setId(1L);
        student.setName("張三");
        //獲取目標類自己的所有成員變量
        Field[] fields = clazz.getDeclaredFields();
        for(Field field:fields) {
//            try {
//                System.out.println(field.get(student));
//            } catch (IllegalArgumentException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            } catch (IllegalAccessException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
            field.setAccessible(true);
            if(field.getName().equals("id")) {
                try {
                    field.set(student, 2L);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else {
                try {
                    field.set(student, "李四");
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            try {
                System.out.println(field.get(student));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("成員變量名稱:"+field.getName());
            System.out.println("成員變量數據類型:"+field.getType().getName());
            System.out.println("訪問權限:"+getModifiers(field.getModifiers()));
        }
        
        System.out.println(student.getId());
        System.out.println(student.getName());
//        System.out.println("*********************");
//        try {
//            Field field = clazz.getField("id");
//            System.out.println(field);
//        } catch (NoSuchFieldException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (SecurityException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        System.out.println("************************");
//        try {
//            Field field = clazz.getDeclaredField("id");
//            System.out.println(field);
//        } catch (NoSuchFieldException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (SecurityException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
    
    public static String getModifiers(int modifier) {
        String result = "";
        switch(modifier) {
        case 0:
            result = "";
            break;
        case 1:
            result = "public";
            break;
        case 2:
            result = "private";
            break;
        case 3:
            result = "protected";
            break;
        }
        return result;
    }
}

 

Test3.java

package com.southwind.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.southwind.entity.Student;

public class Test3 {
    public static void main(String[] args) {
        Class clazz = Student.class;
        Constructor<Student> constructor = null;
        try {
//            constructor = clazz.getConstructor(null);
            constructor = clazz.getConstructor(Long.class,String.class);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        System.out.println(constructor);
        try {
            Student student = constructor.newInstance(3L,"小明");
            System.out.println(student);
            Student student1 = new Student();
            System.out.println(student1);
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
相關文章
相關標籤/搜索