Java 反射使用技巧

一、背景介绍

    大家都知道使用反射能灵活控制java运行时状态,但是使用反射也带来了性能的损耗,不过有时候我们必须使用一些反射来满足我们的需求。那么这个时候就要求我们具备一些反射的 使用技巧;

二、使用技巧介绍

    1,通过setAccessible关闭安全检查,关闭的目的不是因为访问的field/method是私有的,而是因为关闭后对公有或者私有的方法或字段的访问不会再有安全检查.

        Class A = Class.forName("com.xx.xx");
        Method method = A.getDeclaredMethod("methodA");
        method.setAccessible(true);
        method.invoke(A.newInstance());

    2,把已经查找好的method/field 或者实例化的类缓存起来,毕竟类的结构一般是不会变化的.

public Method getMethod(String name, @SuppressWarnings("rawtypes") Class... parameterTypes) throws SecurityException, NoSuchMethodException {

        Method method = classMethodMap.get(name);//classMethodMap used to store method

        if (method == null) {
            method = someClass.getDeclaredMethod(name, parameterTypes);//someClass is the reflect object class
            method.setAccessible(Boolean.TRUE);
            classMethodMap.put(name, method);
        }
        return method;
    }

    3,获取方法或者字段的时候尽量传入方法名或者字段名,这样查找的时候不用遍历所有的方法和字段;

    4,未完继续。。。。。



你可能感兴趣的:(java)