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

时间:2019-07-11
本文章向大家介绍69期-Java SE-024-反射-2-001-002,主要包括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.java

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.java

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.java

package com.southwind.proxy;

public class BMW implements Car {

    @Override
    public String saleCar() {
        // TODO Auto-generated method stub
        return "销售宝马汽车";
    }

}

 

Car.java

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.java

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

 

$flag 上一页 下一页