Java 中的反射

反射

简单来说反射就是运行时获取,检测和调用对象的属性和方法

tips:Java的反射的方法很多,有个小技巧就是带有Declared的方法都是可以访问到非public的。

反射的基本使用

如何获取一个类的Class对象

  1. Class.forName();
        public class RefTest {
            public static void main(String[] args) {
                Class classType = Class.forName("com.javautil.reflecttest.RefTest"); 
            }
        }

  1. 通过某个类的class熟悉来获得
        Class classType2 =  RefTest.class;
  1. 调用某个对象的getClass()方法
        RefTest refTest = new RefTest();

        Class refTestClass = refTest.getClass();

Class 对象提供了大量的实例方法来获取该Class对象所对应类的基本信息

从Class获取信息

创建对象

通过反射创建对象的方式优如下两种:

  • 通过Class 对象的newInstance方法来创建的:
        Object object = classType2.newInstance();

  • 第二种就是通过Constructor 对象来创建的

调用无参构造

        //通过制定形参列表的方式来获取Constructor对象
        Constructor constructor = classType2.getDeclaredConstructor();

        constructor.newInstance();

调用有参数的构造方法

       Constructor constructor2 = classType2.getDeclaredConstructor(String.class);
        constructor2.newInstance("test");

通过源码Class对象newInstance()的源码可以发现,其底层封装了无参数的Constructor对象

    @CallerSensitive
    public T newInstance()
        throws InstantiationException, IllegalAccessException
    {
        if (System.getSecurityManager() != null) {
            checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
        }

        // NOTE: the following code may not be strictly correct under
        // the current Java memory model.

        // 会检查是否缓存了当前类的无参的构造
        if (cachedConstructor == null) {
            if (this == Class.class) {
                throw new IllegalAccessException(
                    "Can not call newInstance() on the Class for java.lang.Class"
                );
            }
            try {
                Class<?>[] empty = {};
                //如果没有就创建一个
                final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
                // Disable accessibility checks on the constructor
                // since we have to do the security check here anyway
                // (the stack depth is wrong for the Constructor's
                // security check to work)
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                                c.setAccessible(true);
                                return null;
                            }
                        });
                //并把它放入到缓存当中去
                cachedConstructor = c;
            } catch (NoSuchMethodException e) {
                throw new InstantiationException(getName());
            }
        }
        Constructor<T> tmpConstructor = cachedConstructor;
        // Security check (same as in java.lang.reflect.Constructor)
        int modifiers = tmpConstructor.getModifiers();
        if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            if (newInstanceCallerCache != caller) {
                Reflection.ensureMemberAccess(caller, this, null, modifiers);
                newInstanceCallerCache = caller;
            }
        }
        // Run constructor
        try {
            //创建一个构造器参数为空的对象返回
            return tmpConstructor.newInstance((Object[])null);
        } catch (InvocationTargetException e) {
            Unsafe.getUnsafe().throwException(e.getTargetException());
            // Not reached
            return null;
        }
    }
方法相关
1. 获取方法

方法的代码都是如下代码为实例

public class RefTest {

    public static void printHello(){
        System.out.println("static method");
    }



    public void printWorld(){
        System.out.println("nonstatic method no args");
    }


    public void printWorld(String msg){
        System.out.println("nonstatic method");
    }

    private void printInfo(String  info){
        System.out.println("private method "+ info);
    }
}
  1. getMethod 返回该Clas类的public 的方法。如果不存在,或者所要获取的方法的访问权限是非public 的,那么将抛出一个NoSuchMethodException
    @CallerSensitive
    public Method getMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        // be very careful not to change the stack depth of this
        // checkMemberAccess call for security reasons
        // see java.lang.SecurityManager.checkMemberAccess
        checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
        Method method = getMethod0(name, parameterTypes);
        if (method == null) {
            throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
        }
        return method;
    }

这个方法接受两个参数 方法名,跟参数的类型。如果我们重写了多个方法getMethod 会根据方法的参数类型来判断我们拿到的Method对象是哪一个。

public static void main(String[] args) throws  Exception{
        Class classType2 =  RefTest.class;
        //创建对象 这里简单介绍一下 后面会有详细的介绍
        Object object = classType2.newInstance();
        Method method = classType2.getMethod("printWorld");
        method.invoke(object);
    }

我们重写了两个printWorld 方法 但是在getMethod 的时候没有传入 方法接受的参数的类型,即就是不接受参数。那么程序就会调用无参数的那个方法,上面的程序打印如下:

nonstatic method no args
  1. getMethods() 不接受参数 ,返回该Class所有的public 方法:源码如下:
    public Method[] getMethods() throws SecurityException {
       
    }
    

它只会返回public 修饰的所有方法,不会返回非public (private 、 protect 、 无修饰符的 都不会返回)

上面的两个都是受限于访问权限的控制,它们都无法获取到非public 的方法

  1. getDeclaredMethod()
   @CallerSensitive
    public Method getDeclaredMethod(String name, Class<?>... parameterTypes){
    }

它是getMethod的扩展版本,为访问非public的方法而提供的

  1. getDeclaredMethods()

它是getMethods的扩展版本,为访问非public的方法而提供的,用法大致相同,不在过多的赘述。

2. 方法的调用

使用反射调用方法使用的是Method 的invoke 方法

  1. 方法有权限调用
        //第一步获取到Class对象
        Class classType2 =  RefTest.class;
        //获取到该Class对象的实例,也就是调用下面方法的对象
        Object object = classType2.newInstance();
        //获取到名称叫printWorld 接受一个参数 类型为String的方法
        Method methodP =  classType2.getMethod("printWorld",String.class);
        //执行调用
        methodP.invoke(object,"hello");

invoke 它接受一个两个(这样是不准确的 第二个是动态参数 )参数 第一个是调用该方法的实例对象,就是这个方法要被哪个对象锁调用,第二个是 参数的值。

  1. 调用没有权限的方法

调用没有访问权限的方法需要在执行invoke方法之前调用:

methodP.setAccessible(false);

setAccessible 方法是定义在AccessibleObject 类之中,Method ,Constructor,Field 都继承了它

所以在访问非public的方法、构造器 、属性的时候 都需要提前调用setAccessible(false);

获取属
public class InfoTest {

    @Deprecated
    private String userName = "456";
    public String password = "123";

    public static void main(String[] args) throws Exception{
       Class classType =  InfoTest.class;
        Field field = classType.getField("password");
        Field field2 = classType.getDeclaredField("userName");
        System.out.println();
        System.out.println(field.getName());
    }
}
获取注解
        Field field2 = classType.getDeclaredField("userName");
        Deprecated  deprecated = field2.getAnnotation(Deprecated.class);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值