反射

Java发射机制是指在运行状态下,对于任意一个类,都可以得到其方法与属性。

发射机制的相关类

类名 用途
Class类 代表类的实体,在运行的Java应用程序中表示类和接口
Field类 代表类的成员变量(成员变量也称为类的属性)
Method类 代表类的方法
Constructor类 代表类的构造方法

class类

  • 获取Class类的方法
获取方法 代码实现
1 通过实例化对象getClass()获取 Class cl = new D().getClass();
2 通过Class.forName()获取 Class cl = Class.forName("practice.D");
3 直接使用对象.class文件 Class cl = D.class;l
  • Class类中的实例化方法
方法 用途
newInstance() 实例化对象
  • 获取类中的属性(fields)
方法 用途
getField(String name) 获得某个公有的属性对象
getFields() 获得所有公有的属性对象
getDeclaredField(String name) 获得某个属性对象
getDeclaredFields() 获得所有属性对象

对属性的操作:

fields[1].getName() //获取属性名称
fields[1].getType().getSimpleName() //获取属性类型名称
int i = fields[1].getModifiers();
String modify = Modifier.toString(i); //获取修饰符
fields[0].set(d,111); //修改值,前提是该类已实例化并且不是private修饰,若是private修饰需要提前打破封装
fields[1].setAccessible(true); //打破封装
    public static void main(String[] args) throws Exception {
        Class c = Class.forName("practice1.D");
        D d = (D) c.newInstance();
        System.out.println(d.a);
        Field[] fields = c.getDeclaredFields();
        fields[0].set(d,111);
        fields[1].setAccessible(true);
        fields[1].set(d,222);
        System.out.println(d.a);
    }
  • 获取类中的注解(Annotations)
方法 用途
getAnnotation(Class annotationClass) 返回该类中与参数类型匹配的公有注解对象
getAnnotations() 返回该类所有的公有注解对象
getDeclaredAnnotation(Class annotationClass) 返回该类中与参数类型匹配的所有注解对象
getDeclaredAnnotations() 返回该类所有的注解对象
  • 获取类中的方法(Methods)
方法 用途
getMethod(String name, Class...<?> parameterTypes) 获得该类某个公有的方法
getMethods() 获得该类所有公有的方法
getDeclaredMethod(String name, Class...<?> parameterTypes) 获得该类某个方法
getDeclaredMethods() 获得该类所有方法

对方法的操作

Method method = c.getDeclaredMethod("play", int.class);
method.invoke(d,3);
  • 获取类中的构造器(Constructor)
方法 用途
getConstructor(Class...<?> parameterTypes) 获得该类中与参数类型匹配的公有构造方法
getConstructors() 获得该类的所有公有构造方法
getDeclaredConstructor(Class...<?> parameterTypes) 获得该类中与参数类型匹配的构造方法
getDeclaredConstructors() 获得该类所有构造方法