java 反射

java反射概念

反射机制就是可以把一个类,类的成员(函数,属性),当成一个对象来操作,希望读者能理解,也就是说,类,类的成员,我们在运行的时候还可以动态地去操作他们.(特别注意运行时)Java反射机制可以让我们在编译期(Compile Time)之外的运行期(Runtime)获得任何一个类的字节码。包括接口、变量、方法等信息。还可以让我们在运行期实例化对象,通过调用get/set方法获取变量的值

  1. package cn.lee.demo;  
  2.   
  3. import java.lang.reflect.Constructor;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.lang.reflect.Method;  
  7. import java.lang.reflect.Modifier;  
  8. import java.lang.reflect.TypeVariable;  
  9.   
  10. public class Main {  
  11.     /** 
  12.      * 为了看清楚Java反射部分代码,所有异常我都最后抛出来给虚拟机处理! 
  13.      * @param args 
  14.      * @throws ClassNotFoundException 
  15.      * @throws InstantiationException 
  16.      * @throws IllegalAccessException 
  17.      * @throws InvocationTargetException  
  18.      * @throws IllegalArgumentException  
  19.      * @throws NoSuchFieldException  
  20.      * @throws SecurityException  
  21.      * @throws NoSuchMethodException  
  22.      */  
  23.     public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, NoSuchFieldException, NoSuchMethodException {  
  24.         // TODO Auto-generated method stub  
  25.           
  26.         //Demo1.  通过Java反射机制得到类的包名和类名  
  27.         Demo1();  
  28.         System.out.println("===============================================");  
  29.           
  30.         //Demo2.  验证所有的类都是Class类的实例对象  
  31.         Demo2();  
  32.         System.out.println("===============================================");  
  33.           
  34.         //Demo3.  通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在],无参构造  
  35.         Demo3();  
  36.         System.out.println("===============================================");  
  37.           
  38.         //Demo4:  通过Java反射机制得到一个类的构造函数,并实现构造带参实例对象  
  39.         Demo4();  
  40.         System.out.println("===============================================");  
  41.           
  42.         //Demo5:  通过Java反射机制操作成员变量, set 和 get  
  43.         Demo5();  
  44.         System.out.println("===============================================");  
  45.           
  46.         //Demo6: 通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等  
  47.         Demo6();  
  48.         System.out.println("===============================================");  
  49.           
  50.         //Demo7: 通过Java反射机制调用类中方法  
  51.         Demo7();  
  52.         System.out.println("===============================================");  
  53.           
  54.         //Demo8: 通过Java反射机制获得类加载器  
  55.         Demo8();  
  56.         System.out.println("===============================================");  
  57.           
  58.     }  
  59.       
  60.     /** 
  61.      * Demo1: 通过Java反射机制得到类的包名和类名 
  62.      */  
  63.     public static void Demo1()  
  64.     {  
  65.         Person person = new Person();  
  66.         System.out.println("Demo1: 包名: " + person.getClass().getPackage().getName() + ","   
  67.                 + "完整类名: " + person.getClass().getName());  
  68.     }  
  69.       
  70.     /** 
  71.      * Demo2: 验证所有的类都是Class类的实例对象 
  72.      * @throws ClassNotFoundException  
  73.      */  
  74.     public static void Demo2() throws ClassNotFoundException  
  75.     {  
  76.         //定义两个类型都未知的Class , 设置初值为null, 看看如何给它们赋值成Person类  
  77.         Class<?> class1 = null;  
  78.         Class<?> class2 = null;  
  79.           
  80.         //写法1, 可能抛出 ClassNotFoundException [多用这个写法]  
  81.         class1 = Class.forName("cn.lee.demo.Person");  
  82.         System.out.println("Demo2:(写法1) 包名: " + class1.getPackage().getName() + ","   
  83.                 + "完整类名: " + class1.getName());  
  84.           
  85.         //写法2  
  86.         class2 = Person.class;  
  87.         System.out.println("Demo2:(写法2) 包名: " + class2.getPackage().getName() + ","   
  88.                 + "完整类名: " + class2.getName());  
  89.     }  
  90.       
  91.     /** 
  92.      * Demo3: 通过Java反射机制,用Class 创建类对象[这也就是反射存在的意义所在] 
  93.      * @throws ClassNotFoundException  
  94.      * @throws IllegalAccessException  
  95.      * @throws InstantiationException  
  96.      */  
  97.     public static void Demo3() throws ClassNotFoundException, InstantiationException, IllegalAccessException  
  98.     {  
  99.         Class<?> class1 = null;  
  100.         class1 = Class.forName("cn.lee.demo.Person");  
  101.         //由于这里不能带参数,所以你要实例化的这个类Person,一定要有无参构造函数哈~  
  102.         Person person = (Person) class1.newInstance();  
  103.         person.setAge(20);  
  104.         person.setName("LeeFeng");  
  105.         System.out.println("Demo3: " + person.getName() + " : " + person.getAge());  
  106.     }  
  107.       
  108.     /** 
  109.      * Demo4: 通过Java反射机制得到一个类的构造函数,并实现创建带参实例对象 
  110.      * @throws ClassNotFoundException  
  111.      * @throws InvocationTargetException  
  112.      * @throws IllegalAccessException  
  113.      * @throws InstantiationException  
  114.      * @throws IllegalArgumentException  
  115.      */  
  116.     public static void Demo4() throws ClassNotFoundException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException  
  117.     {  
  118.         Class<?> class1 = null;  
  119.         Person person1 = null;  
  120.         Person person2 = null;  
  121.           
  122.         class1 = Class.forName("cn.lee.demo.Person");  
  123.         //得到一系列构造函数集合  
  124.         Constructor<?>[] constructors = class1.getConstructors();  
  125.           
  126.         person1 = (Person) constructors[0].newInstance();  
  127.         person1.setAge(30);  
  128.         person1.setName("leeFeng");  
  129.           
  130.         person2 = (Person) constructors[1].newInstance(20,"leeFeng");  
  131.           
  132.         System.out.println("Demo4: " + person1.getName() + " : " + person1.getAge()  
  133.                 + "  ,   " + person2.getName() + " : " + person2.getAge()  
  134.                 );  
  135.           
  136.     }  
  137.       
  138.     /** 
  139.      * Demo5: 通过Java反射机制操作成员变量, set 和 get 
  140.      *  
  141.      * @throws IllegalAccessException  
  142.      * @throws IllegalArgumentException  
  143.      * @throws NoSuchFieldException  
  144.      * @throws SecurityException  
  145.      * @throws InstantiationException  
  146.      * @throws ClassNotFoundException  
  147.      */  
  148.     public static void Demo5() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException, InstantiationException, ClassNotFoundException  
  149.     {  
  150.         Class<?> class1 = null;  
  151.         class1 = Class.forName("cn.lee.demo.Person");  
  152.         Object obj = class1.newInstance();  
  153.           
  154.         Field personNameField = class1.getDeclaredField("name");  
  155.         personNameField.setAccessible(true);  
  156.         personNameField.set(obj, "胖虎先森");  
  157.           
  158.           
  159.         System.out.println("Demo5: 修改属性之后得到属性变量的值:" + personNameField.get(obj));  
  160.           
  161.     }  
  162.       
  163.   
  164.     /** 
  165.      * Demo6: 通过Java反射机制得到类的一些属性: 继承的接口,父类,函数信息,成员信息,类型等 
  166.      * @throws ClassNotFoundException  
  167.      */  
  168.     public static void Demo6() throws ClassNotFoundException  
  169.     {  
  170.         Class<?> class1 = null;  
  171.         class1 = Class.forName("cn.lee.demo.SuperMan");  
  172.           
  173.         //取得父类名称  
  174.         Class<?>  superClass = class1.getSuperclass();  
  175.         System.out.println("Demo6:  SuperMan类的父类名: " + superClass.getName());  
  176.           
  177.         System.out.println("===============================================");  
  178.           
  179.           
  180.         Field[] fields = class1.getDeclaredFields();  
  181.         for (int i = 0; i < fields.length; i++) {  
  182.             System.out.println("类中的成员: " + fields[i]);  
  183.         }  
  184.         System.out.println("===============================================");  
  185.           
  186.           
  187.         //取得类方法  
  188.         Method[] methods = class1.getDeclaredMethods();  
  189.         for (int i = 0; i < methods.length; i++) {  
  190.             System.out.println("Demo6,取得SuperMan类的方法:");  
  191.             System.out.println("函数名:" + methods[i].getName());  
  192.             System.out.println("函数返回类型:" + methods[i].getReturnType());  
  193.             System.out.println("函数访问修饰符:" + Modifier.toString(methods[i].getModifiers()));  
  194.             System.out.println("函数代码写法: " + methods[i]);  
  195.         }  
  196.           
  197.         System.out.println("===============================================");  
  198.           
  199.         //取得类实现的接口,因为接口类也属于Class,所以得到接口中的方法也是一样的方法得到哈  
  200.         Class<?> interfaces[] = class1.getInterfaces();  
  201.         for (int i = 0; i < interfaces.length; i++) {  
  202.             System.out.println("实现的接口类名: " + interfaces[i].getName() );  
  203.         }  
  204.           
  205.     }  
  206.       
  207.     /** 
  208.      * Demo7: 通过Java反射机制调用类方法 
  209.      * @throws ClassNotFoundException  
  210.      * @throws NoSuchMethodException  
  211.      * @throws SecurityException  
  212.      * @throws InvocationTargetException  
  213.      * @throws IllegalAccessException  
  214.      * @throws IllegalArgumentException  
  215.      * @throws InstantiationException  
  216.      */  
  217.     public static void Demo7() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException  
  218.     {  
  219.         Class<?> class1 = null;  
  220.         class1 = Class.forName("cn.lee.demo.SuperMan");  
  221.           
  222.         System.out.println("Demo7: \n调用无参方法fly():");  
  223.         Method method = class1.getMethod("fly");  
  224.         method.invoke(class1.newInstance());  
  225.           
  226.         System.out.println("调用有参方法walk(int m):");  
  227.         method = class1.getMethod("walk",int.class);  
  228.         method.invoke(class1.newInstance(),100);  
  229.     }  
  230.       
  231.     /** 
  232.      * Demo8: 通过Java反射机制得到类加载器信息 
  233.      *  
  234.      * 在java中有三种类类加载器。[这段资料网上截取] 
  235.  
  236.         1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。 
  237.  
  238.         2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类 
  239.  
  240.         3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。 
  241.      *  
  242.      * @throws ClassNotFoundException  
  243.      */  
  244.     public static void Demo8() throws ClassNotFoundException  
  245.     {  
  246.         Class<?> class1 = null;  
  247.         class1 = Class.forName("cn.lee.demo.SuperMan");  
  248.         String nameString = class1.getClassLoader().getClass().getName();  
  249.           
  250.         System.out.println("Demo8: 类加载器类名: " + nameString);  
  251.     }  
  252.       
  253.       
  254.       
  255. }  
  256. /** 
  257.  *  
  258.  * @author xiaoyaomeng 
  259.  * 
  260.  */  
  261. class  Person{  
  262.     private int age;  
  263.     private String name;  
  264.     public Person(){  
  265.           
  266.     }  
  267.     public Person(int age, String name){  
  268.         this.age = age;  
  269.         this.name = name;  
  270.     }  
  271.   
  272.     public int getAge() {  
  273.         return age;  
  274.     }  
  275.     public void setAge(int age) {  
  276.         this.age = age;  
  277.     }  
  278.     public String getName() {  
  279.         return name;  
  280.     }  
  281.     public void setName(String name) {  
  282.         this.name = name;  
  283.     }  
  284. }  
  285.   
  286. class SuperMan extends Person implements ActionInterface  
  287. {  
  288.     private boolean BlueBriefs;  
  289.       
  290.     public void fly()  
  291.     {  
  292.         System.out.println("超人会飞耶~~");  
  293.     }  
  294.       
  295.     public boolean isBlueBriefs() {  
  296.         return BlueBriefs;  
  297.     }  
  298.     public void setBlueBriefs(boolean blueBriefs) {  
  299.         BlueBriefs = blueBriefs;  
  300.     }  
  301.   
  302.     @Override  
  303.     public void walk(int m) {  
  304.         // TODO Auto-generated method stub  
  305.         System.out.println("超人会走耶~~走了" + m + "米就走不动了!");  
  306.     }  
  307. }  
  308. interface ActionInterface{  
  309.     public void walk(int m);  
  310. }  

使用反射的场景

1.工厂模式:Factory类中用反射的话,添加了一个新的类之后,就不需要再修改工厂类Factory了

2.数据库JDBC中通过Class.forName(Driver).来获得数据库连接驱动
3.分析类文件:毕竟能得到类中的方法等等

4.访问一些不能访问的变量或属性:破解别人代码

通过一个对象获得完整的包名和类名

public class TestReflect {
    public static void main(String[] args) throws Exception {
        TestReflect testReflect = new TestReflect();
        System.out.println(testReflect.getClass().getName());
        // 结果 net.xsoftlab.baike.TestReflect
    }
}

http://coding.imooc.com/class/101.html
实例化Class类对象

public class TestReflect {
    public static void main(String[] args) throws Exception {
        Class<?> class1 = null;
        Class<?> class2 = null;
        Class<?> class3 = null;
        // 一般采用这种形式
        class1 = Class.forName("net.xsoftlab.baike.TestReflect");
        class2 = new TestReflect().getClass();
        class3 = TestReflect.class;
        System.out.println("类名称   " + class1.getName());
        System.out.println("类名称   " + class2.getName());
        System.out.println("类名称   " + class3.getName());
    }
}

获取一个对象的父类与实现的接口

public class TestReflect implements Serializable {
    private static final long serialVersionUID = -2862585049955236662L;
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("net.xsoftlab.baike.TestReflect");
        // 取得父类
        Class<?> parentClass = clazz.getSuperclass();
        System.out.println("clazz的父类为:" + parentClass.getName());
        // clazz的父类为: java.lang.Object
        // 获取所有的接口
        Class<?> intes[] = clazz.getInterfaces();
        System.out.println("clazz实现的接口有:");
        for (int i = 0; i < intes.length; i++) {
            System.out.println((i + 1) + ":" + intes[i].getName());
        }
        // clazz实现的接口有:
        // 1:java.io.Serializable
    }
}

通过反射机制实例化一个类的对象

public class TestReflect {
    public static void main(String[] args) throws Exception {
        Class<?> class1 = null;
        class1 = Class.forName("net.xsoftlab.baike.User");
        // 第一种方法,实例化默认构造方法,调用set赋值
        User user = (User) class1.newInstance();
        user.setAge(20);
        user.setName("Rollen");
        System.out.println(user);
        // 结果 User [age=20, name=Rollen]
        // 第二种方法 取得全部的构造函数 使用构造函数赋值
        Constructor<?> cons[] = class1.getConstructors();
        // 查看每个构造方法需要的参数
        for (int i = 0; i < cons.length; i++) {
            Class<?> clazzs[] = cons[i].getParameterTypes();
            System.out.print("cons[" + i + "] (");
            for (int j = 0; j < clazzs.length; j++) {
                if (j == clazzs.length - 1)
                    System.out.print(clazzs[j].getName());
                else
                    System.out.print(clazzs[j].getName() + ",");
            }
            System.out.println(")");
        }
        // 结果
        // cons[0] (java.lang.String)
        // cons[1] (int,java.lang.String)
        // cons[2] ()
        user = (User) cons[0].newInstance("Rollen");
        System.out.println(user);
        // 结果 User [age=0, name=Rollen]
        user = (User) cons[1].newInstance(20, "Rollen");
        System.out.println(user);
        // 结果 User [age=20, name=Rollen]
    }
}
class User {
    private int age;
    private String name;
    public User() {
        super();
    }
    public User(String name) {
        super();
        this.name = name;
    }
    public User(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + "]";
    }
}

通过反射机制调用某个类的方法

public class TestReflect {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("net.xsoftlab.baike.TestReflect");
        // 调用TestReflect类中的reflect1方法
        Method method = clazz.getMethod("reflect1");
        method.invoke(clazz.newInstance());
        // Java 反射机制 - 调用某个类的方法1.
        // 调用TestReflect的reflect2方法
        method = clazz.getMethod("reflect2", int.class, String.class);
        method.invoke(clazz.newInstance(), 20, "张三");
        // Java 反射机制 - 调用某个类的方法2.
        // age -> 20. name -> 张三
    }
    public void reflect1() {
        System.out.println("Java 反射机制 - 调用某个类的方法1.");
    }
    public void reflect2(int age, String name) {
        System.out.println("Java 反射机制 - 调用某个类的方法2.");
        System.out.println("age -> " + age + ". name -> " + name);
    }
}

反射机制的动态代理

TestReflect testReflect = new TestReflect();
        System.out.println("类加载器  " + testReflect.getClass().getClassLoader().getClass().getName());
package net.xsoftlab.baike;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//定义项目接口
interface Subject {
    public String say(String name, int age);
}
// 定义真实项目
class RealSubject implements Subject {
    public String say(String name, int age) {
        return name + "  " + age;
    }
}
class MyInvocationHandler implements InvocationHandler {
    private Object obj = null;
    public Object bind(Object obj) {
        this.obj = obj;
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object temp = method.invoke(this.obj, args);
        return temp;
    }
}
/**
 * 在java中有三种类类加载器。
 * 
 * 1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。
 * 
 * 2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jrelibext目录中的类
 * 
 * 3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。
 * 
 * 如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。
 * 
 * @author xsoftlab.net
 * 
 */
public class TestReflect {
    public static void main(String[] args) throws Exception {
        MyInvocationHandler demo = new MyInvocationHandler();
        Subject sub = (Subject) demo.bind(new RealSubject());
        String info = sub.say("Rollen", 20);
        System.out.println(info);
    }
}

4反射机制的应用实例

在泛型为Integer的ArrayList中存放一个String类型的对象。

public class TestReflect {
    public static void main(String[] args) throws Exception {
        ArrayList<Integer> list = new ArrayList<Integer>();
        Method method = list.getClass().getMethod("add", Object.class);
        method.invoke(list, "Java反射机制实例。");
        System.out.println(list.get(0));
    }
}

通过反射取得并修改数组的信息

public class TestReflect {
    public static void main(String[] args) throws Exception {
        int[] temp = { 1, 2, 3, 4, 5 };
        Class<?> demo = temp.getClass().getComponentType();
        System.out.println("数组类型: " + demo.getName());
        System.out.println("数组长度  " + Array.getLength(temp));
        System.out.println("数组的第一个元素: " + Array.get(temp, 0));
        Array.set(temp, 0, 100);
        System.out.println("修改之后数组第一个元素为: " + Array.get(temp, 0));
    }
}

通过反射机制修改数组的大小

public class TestReflect {
    public static void main(String[] args) throws Exception {
        int[] temp = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int[] newTemp = (int[]) arrayInc(temp, 15);
        print(newTemp);
        String[] atr = { "a", "b", "c" };
        String[] str1 = (String[]) arrayInc(atr, 8);
        print(str1);
    }
    // 修改数组大小
    public static Object arrayInc(Object obj, int len) {
        Class<?> arr = obj.getClass().getComponentType();
        Object newArr = Array.newInstance(arr, len);
        int co = Array.getLength(obj);
        System.arraycopy(obj, 0, newArr, 0, co);
        return newArr;
    }
    // 打印
    public static void print(Object obj) {
        Class<?> c = obj.getClass();
        if (!c.isArray()) {
            return;
        }
        System.out.println("数组长度为: " + Array.getLength(obj));
        for (int i = 0; i < Array.getLength(obj); i++) {
            System.out.print(Array.get(obj, i) + " ");
        }
        System.out.println();
    }
}

将反射机制应用于工厂模式

interface fruit {
    public abstract void eat();
}
class Apple implements fruit {
    public void eat() {
        System.out.println("Apple");
    }
}
class Orange implements fruit {
    public void eat() {
        System.out.println("Orange");
    }
}
class Factory {
    public static fruit getInstance(String ClassName) {
        fruit f = null;
        try {
            f = (fruit) Class.forName(ClassName).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
/**
 * 对于普通的工厂模式当我们在添加一个子类的时候,就需要对应的修改工厂类。 当我们添加很多的子类的时候,会很麻烦。
 * Java 工厂模式可以参考
 * http://baike.xsoftlab.net/view/java-factory-pattern
 * 
 * 现在我们利用反射机制实现工厂模式,可以在不修改工厂类的情况下添加任意多个子类。
 * 
 * 但是有一点仍然很麻烦,就是需要知道完整的包名和类名,这里可以使用properties配置文件来完成。
 * 
 * java 读取 properties 配置文件 的方法可以参考
 * http://baike.xsoftlab.net/view/java-read-the-properties-configuration-file
 * 
 * @author xsoftlab.net
 */
public class TestReflect {
    public static void main(String[] args) throws Exception {
        fruit f = Factory.getInstance("net.xsoftlab.baike.Apple");
        if (f != null) {
            f.eat();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41205419/article/details/79917511