注解和反射 — 反射

本博客是参考秦疆老师的Java教学视频整理而来
如有侵权,联系立删

1. 静态语言与动态语言

1.1 动态语言

​  是一类在运行时可以改变其结构的语言:例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除或是其他结构上的变化。通俗点说就是在运行时代码可以根据某些条件改变自身结构。

  主要动态语言:Object-C、C#、JavaScript、PHP、Python等。

1.2 静态语言

  与动态语言相对应的,运行时结构不可变的语言就是静态语言。如Java、C、C++、

  Java不是动态语言,但Java可以称之为“准动态语言”。即Java有一定的动态性,我们可以利用反射机制获得类似动态语言的特性。Java的动态性让编程的时候更加灵活。

2. 反射Reflection

  反射reflection是java被视为同台语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。

Class c = Class.forName("java.lang.String");

   加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以我们形象地称之为“反射”。

  正常方法:引入需要的包类名称 --》通过new实例化 --》取得实例化对象

​ 反射方法:实例化对象 --》getClass()方法 --》得到完整的包类名称

2.1 Java反射机制提供的功能

  • 在运行时判断任意一个对象所属的类;

  • 在运行时构造任意一个类的对象;

  • 在运行时判断任意一个类所具有的成员变量和方法;

  • 在运行时获取泛型信息;

  • 在运行时调用任意一个对象的成员变量和方法;

  • 在运行时处理注解;

  • 生成动态代理;

2.2 Java反射优点和缺点

优点:可以实现动态创建对象和编译,体现出很大的灵活性。

 ​缺点:对性能有影响。使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它满足我们的要求。这些操作总是慢于直接执行相同的操作。

2.3 反射相关的主要API

  • java.lang.class:代表一个类;
  • java.lang.reflect.Method:代表类的方法;
  • java.lang.reflect.Field:代表类的成员变量;
  • java.lang.reflect.Constructor:代表类的构造器;

示例:

package com.jiuhong.reflection;

//什么叫反射
public class Test1 {
    public static void main(String[] args) throws ClassNotFoundException {
        // 通过反射获取类的class对象
        Class c1 = Class.forName("com.jiuhong.reflection.User");
        System.out.println(c1);

        // 一个类被加载后,类的整个结构都会被封装在Class对象
        // 一个类在内存中只有一个Class对象
        Class c2 = Class.forName("com.jiuhong.reflection.User");
        Class c3 = Class.forName("com.jiuhong.reflection.User");
        Class c4 = Class.forName("com.jiuhong.reflection.User");
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
        System.out.println(c4.hashCode());
    }
}

//实体类
class User{
    private String name;
    private int id;
    private int age;

    public User() {
    }

    public User(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

运行结果:
java
class com.jiuhong.reflection.User
460141958
460141958
460141958

3. Class类

​  对象映射后可以得到的信息:某个类的属性、方法和构造器、某个类到底实现了哪些接口。对于每个类而言,JRE都为其保留一个不变的Class类型的对象。一个Class对象包含了特定某个结构的有关信息。

  • Class本身也是一个类;

  • Class对象只能由系统建立,程序员只能获得Class对象;

  • 一个加载的类在JVM中只会有一个Class实例;

  • 一个Class对象对应的是一个加载到JVM中的一个.class文件;

  • 每个类的实例都会记得自己是由哪个Class实例所生成;

  • 通过Class可以完整地得到一个类中的所有被加载的结构;

  • Class类是Reflection的根源,针对任何你想动态加载、运行的类,唯有先获得相应的Class对象。

3.1 Class类的常用方法

方法名功能说明
static ClassforName(String name)返回指定类名name的Class对象
Object newInsatance()调用缺省构造函数,返回Class对象的一个实例
getName()返回此Class对象所表示的实体(类、接口、数组类或void)的名称
Class getSuperClass()返回当前Class对象的父类的Class对象
Class[] getinterfaces()获取当前Class对象的接口
ClassLoader getClassLoader()返回该类的类加载器
Constructor[] getConstructors()返回一个包含某些Constructor对象的数组
Method getMothed(String name, Class… T)返回一个Method对象,此对象的形参类型为paramType
Field[] getDeclaredFields()返回Field对象的一个数组

3.2 获得Class类的实例

  • 若已知具体的类,通过类的class属性获取,该方法最为安全可靠,程序性能最高。
Class clazz = Person.class;
  • 已知某个类的实例,调用该实例的getClass()方法获取Class对象。
Class clazz = person.getClass();
  • 已知一个类的全类名,且该类在类路径下,可通过Class类的静态方法forName()获取。程序可能会抛出ClassNotFoundException异常。
Class clazz = Class.forName("demo01.Student");
  • 内置基本数据类型可以直接用类名.Type。
Class clazz = Integer.TYPE;
  • 还可以利用ClassLoader。

示例:

package com.jiuhong.reflection;

//测试Class类的创建方式有哪些
public class Test2 {
    public static void main(String[] args) throws ClassNotFoundException {

        Person person = new Student();
        System.out.println("这个人是:"+person.name);

        // 方式1:通过对象获得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        // 方法2:通过forName方法获得
        Class c2 = Class.forName("com.jiuhong.reflection.Student");
        System.out.println(c2.hashCode());

        // 方法3:通过类名.class获得
        Class c3 = Student.class;
        System.out.println(c3.hashCode());


        // 基本内置类型的包装类都有一个Type属性
        Class c4 = Integer.TYPE;
        System.out.println(c4);

        // 获得父类类型
        Class c5 = c1.getSuperclass();
        System.out.println(c5);
    }

}


class Person{
    int age;
    String name;

    public Person() {
    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

class Student extends Person{
    public Student() {
        this.name = "学生";
    }
}

class Teacher extends Person{
    public Teacher() {
        this.name = "老师";
    }
}

输出结果:

这个人是:学生
460141958
460141958
460141958
int
class com.jiuhong.reflection.Person

3.3 哪些类型可以有Class对象?

  • class:外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类。
  • interface:接口;
  • []:数组;
  • enum:枚举;
  • annotation:注解@interface
  • primitive type:基本数据类型
  • void

示例:

package com.jiuhong.reflection;

import java.lang.annotation.ElementType;

public class Test3 {
    public static void main(String[] args) {
        Class c1 = Object.class;          //类
        Class c2 = Comparable.class;      //接口
        Class c3 = String[].class;        //一维数组
        Class c4 = int[][].class;         //二维数组
        Class c5 = Override.class;        //注解
        Class c6 = int.class;             //基本类型
        Class c7 = Integer.class;         //基本类型包装类
        Class c8 = ElementType.class;     //枚举
        Class c9 = void.class;            //void
        Class c10 = Class.class;          //Class

        System.out.println(c1 );
        System.out.println(c2 );
        System.out.println(c3 );
        System.out.println(c4 );
        System.out.println(c5 );
        System.out.println(c6 );
        System.out.println(c7 );
        System.out.println(c8 );
        System.out.println(c9 );
        System.out.println(c10);

        // 只要数组元素和维度一样,就是同一个Class
        System.out.println("=============================================");
        int[] a = new int[10];
        int[] b = new int[100];
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());

    }
}

结果:

class java.lang.Object
interface java.lang.Comparable
class [Ljava.lang.String;
class [[I
interface java.lang.Override
int
class java.lang.Integer
class java.lang.annotation.ElementType
void
class java.lang.Class
=============================================
460141958
460141958

3.4 获取运行时类的完整结构

​  通过反射获取运行时类的完整结构:Field、Method、Constructor、Superclass、Interface、Annotation。

示例:

package com.jiuhong.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test7 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        Staff staff = new Staff();
        Class c1 = staff.getClass();

        // 获得类的名字
        System.out.println("==获得类的名字======================");
        System.out.println(c1.getName());
        System.out.println(c1.getSimpleName());

        // 获得类的属性
        System.out.println("==获得类的属性======================");
        Field[] fields = c1.getFields();                        // 获得本类及其父类的public属性
        for (int i = 0; i < fields.length; i++) {
            System.out.println("field: "+fields[i]);
        }

        Field[] declaredFields = c1.getDeclaredFields();        // 获得本类所有属性
        for (Field declaredField : declaredFields) {
            System.out.println("declaredField: "+declaredField);
        }

        // 获得指定的属性
        System.out.println(c1.getDeclaredField("age"));

        // 获得类的方法
        System.out.println("==获得类的方法======================");
        Method[] methods = c1.getMethods();                     // 获得本类极其父类的所有public方法
        for (Method method : methods) {
            System.out.println("methods: "+method);
        }

        Method[] declaredMethods = c1.getDeclaredMethods();     // 获得本类所有的方法
        for (Method declaredMethod : declaredMethods) {
            System.out.println("declaredMethod: " + declaredMethod);
        }

        // 获得指定的方法
        System.out.println("==获得指定的方法======================");
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        Method setAge  = c1.getMethod("setAge", int.class);
        System.out.println(getName);
        System.out.println(setName);
        System.out.println(setAge);

        // 获得指定构造器
        System.out.println("==获得指定构造器======================");
        System.out.println(c1.getDeclaredConstructor(null));
        System.out.println(c1.getDeclaredConstructor(String.class, int.class, int.class));

    }
}


class Staff{
    private int    id;
    private String name;
    private int    age;

    public Staff() {
    }

    public Staff(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private void test(){}
}

运行结果:

==获得类的名字======================
com.jiuhong.reflection.Staff
Staff
==获得类的属性======================
declaredField: private int com.jiuhong.reflection.Staff.id
declaredField: private java.lang.String com.jiuhong.reflection.Staff.name
declaredField: private int com.jiuhong.reflection.Staff.age
private int com.jiuhong.reflection.Staff.age
==获得类的方法======================
methods: public java.lang.String com.jiuhong.reflection.Staff.getName()
methods: public int com.jiuhong.reflection.Staff.getId()
methods: public void com.jiuhong.reflection.Staff.setName(java.lang.String)
methods: public void com.jiuhong.reflection.Staff.setAge(int)
methods: public int com.jiuhong.reflection.Staff.getAge()
methods: public void com.jiuhong.reflection.Staff.setId(int)
methods: public final void java.lang.Object.wait() throws java.lang.InterruptedException
methods: public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
methods: public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
methods: public boolean java.lang.Object.equals(java.lang.Object)
methods: public java.lang.String java.lang.Object.toString()
methods: public native int java.lang.Object.hashCode()
methods: public final native java.lang.Class java.lang.Object.getClass()
methods: public final native void java.lang.Object.notify()
methods: public final native void java.lang.Object.notifyAll()
declaredMethod: public java.lang.String com.jiuhong.reflection.Staff.getName()
declaredMethod: public int com.jiuhong.reflection.Staff.getId()
declaredMethod: public void com.jiuhong.reflection.Staff.setName(java.lang.String)
declaredMethod: private void com.jiuhong.reflection.Staff.test()
declaredMethod: public void com.jiuhong.reflection.Staff.setAge(int)
declaredMethod: public int com.jiuhong.reflection.Staff.getAge()
declaredMethod: public void com.jiuhong.reflection.Staff.setId(int)
==获得指定的方法======================
public java.lang.String com.jiuhong.reflection.Staff.getName()
public void com.jiuhong.reflection.Staff.setName(java.lang.String)
public void com.jiuhong.reflection.Staff.setAge(int)
==获得指定构造器======================
public com.jiuhong.reflection.Staff()
public com.jiuhong.reflection.Staff(java.lang.String,int,int)

3.5 反射操作泛型

  为了通过反射操作这些类型,Java新增了ParameterizedType、GenericArrayType、TypeVariable和WildcardType几种类型来代表不能被归一到Class类的类型但是又和原始类型齐名的类型。

  • java.lang.reflect.Type:java语言中所有类型的公共父接口;
  • ParameterizedType:表示一种参数化类型,比如Collection;
  • GenericArrayType:表示一种元素类型是参数化类型或者类型变量的数组类型;
  • TypeVariable:是各种类型变量的公共父接口;
  • WildcardType:代表一种通配符类型表达式;

示例:

package com.jiuhong.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class Test11 {
    public void test1(Map<String,User> map, List<User> list, int gender){
        System.out.println("test1");
    }

    public Map<String,User> test2() {
        System.out.println("test2");
        return null;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        // 获得test1方法的参数信息
        System.out.println("== test1 =============================");
        Method test1 = Test11.class.getDeclaredMethod("test1", Map.class, List.class, int.class);
        Type[] genericParameterTypes = test1.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("#"+genericParameterType);

            if (genericParameterType instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (int i = 0; i < actualTypeArguments.length; i++) {
                    System.out.println(actualTypeArguments[i]);
                }
            }
        }

        // 获得test2方法的返回信息
        System.out.println("== test2 =============================");
        Method test2 = Test11.class.getDeclaredMethod("test2", null);
        Type genericReturnType = test2.getGenericReturnType();
        System.out.println("#"+genericReturnType);

        if (genericReturnType instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }
    }
}

运行结果:

== test1 =============================
#java.util.Map<java.lang.String, com.jiuhong.reflection.User>
class java.lang.String
class com.jiuhong.reflection.User
#java.util.List<com.jiuhong.reflection.User>
class com.jiuhong.reflection.User
#int
== test2 =============================
#java.util.Map<java.lang.String, com.jiuhong.reflection.User>
class java.lang.String
class com.jiuhong.reflection.User

3.6 反射操作注解

示例:

package com.jiuhong.reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

// 练习反射操作注解
public class Test10 {
    public static void main(String[] args) throws NoSuchFieldException {
        Class c1 = Student2.class;

        // 通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        // 获得注解的value
        TableAnnotation tableAnnotation = (TableAnnotation)c1.getAnnotation(TableAnnotation.class);
        String value = tableAnnotation.value();
        System.out.println(value);

        // 获得类的指定的注解
        Field id = c1.getDeclaredField("id");
        FieldAnnotation annotation = id.getAnnotation(FieldAnnotation.class);
        System.out.println(annotation.columName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());

    }
}

@TableAnnotation("db_student")
class Student2{
    @FieldAnnotation(columName = "db_id", type = "int", length = 10)
    int id;

    @FieldAnnotation(columName = "db_name", type = "varchar", length = 30)
    String name;

    @FieldAnnotation(columName = "db_age", type = "int", length = 10)
    int age;

    public Student2() {
    }

    public Student2(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAnnotation{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnnotation{
    String columName();
    String type();
    int length();
}

运行结果:

@com.jiuhong.reflection.TableAnnotation(value=db_student)
db_student
db_id
int
10
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值