反射

1. 什么是反射?

Java的反射是指在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。

2. 反射的用途

我们知道反射机制允许程序在运行时取得任何一个已知名称的class的内部信息,包括包括其modifiers(修饰符)、fields(属性)、methods(方法)等,并可于运行时改变fields内容或调用methods。

那么我们便可以更灵活的编写代码,代码可以在运行时装配,无需在组件之间进行源代码链接,降低代码的耦合度;还有动态代理的实现等等;但是需要注意的是反射使用不当会造成很高的资源消耗!

3. 反射的API介绍

我们以一个Person类为例:

public class Person<T> {
    private int age=18;
    public String name="tom";
    public Person() {
    }
    public Person(int age, String name) {
        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;
    }

    public void show(){
        System.out.println("show run!");
    }
    private void say(){
        System.out.println("say run!");
    }
}

要对该类进行反射,我们先要获取这个类对应的字节码文件对象。

3.1 获取字节码文件对象的三种方式

//1、通过对象调用 getClass() 方法来获取,通常应用在:比如你传过来一个 Object
//  类型的对象,而我不知道你具体是什么类,用这种方法
  Person p1 = new Person();
  Class c1 = p1.getClass();

//2、直接通过 类名.class 的方式得到,该方法最为安全可靠,程序性能更高
//  这说明任何一个类都有一个隐含的静态成员变量 class
  Class c2 = Person.class;

//3、通过 Class 对象的 forName() 静态方法来获取,用的最多,参数为类的全名
//   但可能抛出 ClassNotFoundException 异常
  Class c3 = Class.forName("com.lfx.test.Person");

注意:一个类在虚拟机中只会有一个 Class 实例,即我们对上面获取的 c1,c2,c3进行 equals 比较,发现都是true

查阅API之后,我们发现字节码文件对象(即Class对象)有很多获取类信息的方法:

  • getName():获得类的完整名字。   
  • getFields():获得类的public类型的属性。   
  • getDeclaredFields():获得类的所有属性,包括private声明的。 
  • getMethods():获得类的public类型的方法。   
  • getDeclaredMethods():获得类的所有方法,包括private声明的 
  • getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。   
  • getConstructors():获得类的public类型的构造方法。   
  • getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。   
  • newInstance():通过类的不带参数的构造方法创建这个类的一个对象。

3.2 获取对象的属性、方法、构造器

获取到了Class对象后,我们可以调用Class的方法,获取对象的属性、方法、构造器。

示例代码:

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
    //通过第二种方式获取Class对象
    Class c2 = Person.class;
    //获得类完整的名字
    String className = c2.getName();
    System.out.println(className);

    //获得类的public类型的属性。
    Field[] fields = c2.getFields();
    for(Field field : fields){
        System.out.println(field.getName());
    }

    //获得类的所有属性。包括私有的
    Field [] allFields = c2.getDeclaredFields();
    for(Field field : allFields){
        System.out.println(field.getName());
    }

    //获得类的public类型的方法。这里包括 Object 类的一些方法
    Method[] methods = c2.getMethods();
    for(Method method : methods){
        System.out.println(method.getName());//wait equls toString hashCode等
    }

    //获得类的所有方法。
    Method [] allMethods = c2.getDeclaredMethods();
    for(Method method : allMethods){
        System.out.println(method.getName());//show say
    }

    //获得指定的属性
    Field f1 = c2.getField("name");
    System.out.println(f1);
    //获得指定的私有属性
    Field f2 = c2.getDeclaredField("age");
    //启用和禁用访问安全检查的开关,值为 true,则表示反射的对象在使用时应该取消 java 语言的访问检查;反之不取消
    f2.setAccessible(true);
    System.out.println(f2);

    //创建这个类的一个对象
    Object p2 =  c2.newInstance();
    //将 p2 对象的  f2 属性赋值为 20,f2 属性即为 私有属性 age
    f2.set(p2,20);
    //使用反射机制可以打破封装性,导致了java对象的属性不安全。
    System.out.println(f2.get(p2)); //20

    //获取构造方法
    Constructor[] constructors = c2.getConstructors();
    for(Constructor constructor : constructors){
        System.out.println(constructor.toString());
    }
}

3.3 获取泛型类型

我们定义一个Person的子类来演示如何获取泛型类型:

public class Student extends Person<String> {
    public static void main(String[] args) {
        Student st=new Student();
        Class clazz=st.getClass();
        //getSuperclass()获得该类的父类:class com.lfx.test.Person
        System.out.println(clazz.getSuperclass());
        //getGenericSuperclass()获得带有泛型的父类
        //Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
        Type type=clazz.getGenericSuperclass();
        //输出type: com.lfx.test.Person<java.lang.String>
        System.out.println(type);
        //ParameterizedType是Type的子类,表示参数化类型,即泛型
        ParameterizedType p=(ParameterizedType)type;
        //输出p: com.lfx.test.Person<java.lang.String>
        System.out.println(p);
        //getActualTypeArguments获取参数化类型的数组,泛型可能有多个,例如Map<String,Object>
        Class c=(Class) p.getActualTypeArguments()[0];
        //输出泛型类型:class java.lang.String
        System.out.println(c);
    }
}

3.4 获取注解

我们先自定义一些运行期的注解:

public class MyAnnotation {
    /**
     * 注解类
     */
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyClassAnnotation {
        String value();
    }

    /**
     * 构造方法注解
     */
    @Target(ElementType.CONSTRUCTOR)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyConstructorAnnotation {
        String value();
    }

    /**
     * 方法注解
     */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyMethodAnnotation {
        String value();
    }

    /**
     * 字段注解
     */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyFieldAnnotation {
        String value();
    }
    /**
     * 可以同时应用到类和方法上
     */
    @Target({ ElementType.TYPE, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyClassAndMethodAnnotation {
       String value();
    }

}

我们对Person类添加自定义的注解,用于测试反射是如何获取注解的:

@MyClassAnnotation("测试获取类注解")
@MyClassAndMethodAnnotation("测试获取多个类注解")
public class Person<T> {
    @MyFieldAnnotation("测试获取私有属性注解")
    private int age=18;
    @MyFieldAnnotation("测试获取公共属性注解")
    public String name="tom";
    @MyConstructorAnnotation("测试获取空参构造器注解")
    public Person() {
    }
    @MyConstructorAnnotation("测试获取有参构造器注解")
    public Person(int age, String name) {
        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;
    }
    @MyMethodAnnotation("测试获取公共方法注解")
    public void show(){
        System.out.println("show run!");
    }
    @MyMethodAnnotation("测试获取私有方法注解")
    private void say(){
        System.out.println("say run!");
    }
}

反射获取注解代码:

public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        //通过第二种方式获取Class对象
        Class c2 = Person.class;
        //获得类完整的名字
        String className = c2.getName();
        System.out.println(className);

        //获取类上指定名称的注解
        MyClassAnnotation myClassAnnotation = (MyClassAnnotation) c2.getAnnotation(MyClassAnnotation.class);
        //输出类指定注解的value值:
        System.out.println(myClassAnnotation.value());

        //获取类上所有注解
        Annotation[] annotations = c2.getAnnotations();
        //输出类上所有注解:
        for(Annotation annotation : annotations){
            System.out.println(annotation.toString());
        }

        //获取所有构造方法的指定注解:
        Constructor[] constructors = c2.getConstructors();
        for(Constructor constructor : constructors){
            MyConstructorAnnotation myConstructorAnnotation = (MyConstructorAnnotation) constructor.getAnnotation(MyConstructorAnnotation.class);
            //输出所有构造方法指定注解的value值
            System.out.println(myConstructorAnnotation.value());
        }

        //获得公有字段指定名称的注解。
        Field field = c2.getField("name");
        MyFieldAnnotation fieldAnnotation = field.getAnnotation(MyFieldAnnotation.class);
        //输出公有字段指定名称注解的value值
        System.out.println(fieldAnnotation.value());

        //获得私有字段指定名称的注解。
        Field privateField = c2.getDeclaredField("age");
        MyFieldAnnotation privateFieldAnnotation = privateField.getAnnotation(MyFieldAnnotation.class);
        //输出私有字段指定名称注解的value值
        System.out.println(privateFieldAnnotation.value());

        //获得公有方法指定名称的注解
        Method method = c2.getMethod("show");
        MyMethodAnnotation myMethodAnnotation = method.getAnnotation(MyMethodAnnotation.class);
        //输出公有方法指定名称的注解的value
        System.out.println(myMethodAnnotation.value());

        //获得私有方法指定名称的注解
        Method privateMethod = c2.getDeclaredMethod("say");
        MyMethodAnnotation myPrivateMethodAnnotation =privateMethod.getAnnotation(MyMethodAnnotation.class);
        //输出公有方法指定名称的注解的value
        System.out.println(myPrivateMethodAnnotation.value());
    }
posted @ 2020-11-17 14:15  渺渺孤烟起  阅读(54)  评论(0)    收藏  举报