1. 创建实例。

    反射通过:

    Class<?> c = String.class;
    Object str = c.newInstance();
    

    与new的区别:

    • new:强类型。相对高效。能调用任何public构造。
    • newInstance: 弱类型。低效率。只能调用无参构造,是实现IOC、反射、面对接口编程 和 依赖倒置 等技术方法的必然选择,new 只能实现具体类的实例化,不适合于接口编程。

    正因为newInstance只能调用无参构造,所以Constructor对象就十分有必要了:

    Class<?> c = String.class;
    Constructor constructor = c.getConstrutor(String.class);
    Object o = constructor.newInstance("cc");
    

    通过Constructor我们可以获取对应的构造器构造对象。

  2. setAccessible(boolean)方法,当参数为true时,可以禁止安全检查。这样做可以实现两:

    • 加速,因为无需安全检查,所以会使得方法更快。
    Class c = App.class;
    try {
        //Constructor con =  c.getDeclaredConstructor();
        Object obj = c.newInstance();
        Method method = c.getDeclaredMethod("print");
        long costTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            method.invoke(obj);
        }
        System.out.println("method cost: "+ (System.currentTimeMillis()-costTime));
        method.setAccessible(true);
        costTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            method.invoke(obj);
        }
        System.out.println("method cost: "+ (System.currentTimeMillis()-costTime));
        //con.setAccessible(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    通过以上代码验证,提升起码25%

    • 可以使用私有方法。甚至可以调用私有构造函数。
    Class c = A
    Constructor con =  c.getDeclaredConstructor();
    con.setAccessible(true);