反射

Java Reflection可以在运行时处理类,接口,字段,方法等,而事先不需要知道类名、方法名
核心包java.lang.reflect

Class类

java.lang.Class类是所有反射操作的入口点,所有的类型包括基本数据类型和数组都有对应的Class对象

虚拟机为每个类型管理一个Class对象

获取Class对象

Class cl = MyObject.class
Class cl = Class.forName(className); //如果在运行时无法在`classpath`中找到,会产生ClassNotFoundException
Class cl = myObject.getClass();//通过超类Object获取

类名称

Class aClass = ... //获取Class对象
String className = aClass.getName(); //完整的名称,包括包名
String simpleClassName = aClass.getSimpleName(); //简称

类修饰符

Java修饰符有 public、protected、private、final、static、strict、abstract 、native、volatile、transient、synchronized和 interface 。返回值为int,对应不同的标志位。

Class  aClass = ... //获取Class对象
int modifiers = aClass.getModifiers();

通过java.lang.reflect.Modifier类的静态方法分析返回的数值

Modifier.toString();
Modifier.isAbstract();
...

包信息

Class  aClass = ... //获取Class对象
Package package = aClass.getPackage();

Package 对应使 java.lang.Package,可以获取Manifest文件中关于package的信息

超类

Class superclass = aClass.getSuperclass();

实现接口

Class[] interfaces = aClass.getInterfaces();

返回一个Class数组,可能实现了多个接口
只返回明确声明实现的接口,如果超类实现了一个接口,子类不会返回该接口


构造器Constructors

java.lang.reflect.Constructor

Constructor[] constructors = aClass.getConstructors();
 // 获取特定参数类型的构造器,没有抛出异常 NoSuchMethodException
Constructor constructor = aClass.getConstructor(new Class[]{String.class});

//获取构造器,包括私有的
getDeclaredConstructors()
getDeclaredConstructor(Class<?>... parameterTypes)

获取Constructor参数

Constructor constructor = ... // 获取Constructor对象
Class[] parameterTypes = constructor.getParameterTypes();

如果不带任何参数,返回一个长度为0的数组

使用构造函数实例化对象

//get constructor that takes a String as argument
Constructor constructor = MyObject.class.getConstructor(String.class);

MyObject myObject = (MyObject) constructor.newInstance("constructor-arg1");

字段Fields

ava.lang.reflect.Field 检查成员变量,并且在运行时读取或者设定数值

//仅获取public字段
Field[] method = aClass.getFields();
Field field = aClass.getField("someField"); // 如果已经知道了字段的名称,没有找到NoSuchFieldException

//访问Class的全部字段,包括private
Class.getDeclaredField(String name)
Class.getDeclaredFields()

字段的名称和类型

String fieldName = field.getName();
Class fieldType = field.getType();

获取和设定字段的值

Class  aClass = MyObject.class
Field field = aClass.getField("someField");

MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);

field.set(objetInstance, value);

如果字段值为static,参数可以忽略为null

如果是私有的字段,需要先调用超类AccessibleObject的setAcessible(true),抑制Java语言的访问检查
AccessibleObject.setAcessible(fields,true)设置


方法 Methods

java.lang.reflect.Method

Method[] method = aClass.getMethods();
Method method = aClass.getMethod("doSomething", new Class[]{String.class});

//如果第二个参数为null,就把它当做一个空字符串,相当于没有参数
public Method getMethod(String methodName,  Class<?>... parameterTypes)
                 throws NoSuchMethodException,

//获取私有方法
 Class.getDeclaredMethods()
 Class.getDeclaredMethod(String name, Class[] parameterTypes)

获取参数和返回类型

Class[] parameterTypes = method.getParameterTypes();
Class returnType = method.getReturnType();

调用方法

Object returnValue = method.invoke(null, "parameter-value1");
invoke(Object obj, Object... args)

如果是静态方法,第一个参数可以置为null,如果不需要参数,可以传入null或者长度为0的数组

getter和setter方法

getter:名字以get开始,没有参数,返回一个值
setter:名字以set开始,有一个参数,返回值不确定

public static void printGettersSetters(Class aClass){
  Method[] methods = aClass.getMethods();

  for(Method method : methods){
    if(isGetter(method)) System.out.println("getter: " + method);
    if(isSetter(method)) System.out.println("setter: " + method);
  }
}

public static boolean isGetter(Method method){
  if(!method.getName().startsWith("get"))      return false;
  if(method.getParameterTypes().length != 0)   return false;  
  if(void.class.equals(method.getReturnType()) return false;
  return true;
}

public static boolean isSetter(Method method){
  if(!method.getName().startsWith("set")) return false;
  if(method.getParameterTypes().length != 1) return false;
  return true;
}

注解 Annotations

annotation.getClass().getMethod(method).invoke(annotation);//获取注解内容

Class Annotations

Class aClass = TheClass.class;
Annotation[] annotations = aClass.getAnnotations();
Annotation annotation = aClass.getAnnotation(MyAnnotation.class);//获得特定的类注解

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("name: " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
}

Method Annotations

Method method = ... //obtain method object
Annotation[] annotations = method.getDeclaredAnnotations();
Annotation annotation = method.getAnnotation(MyAnnotation.class);//明确获取

Parameter Annotations

Method method = ... //obtain method object
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();

int i=0;
for(Annotation[] annotations : parameterAnnotations){
  Class parameterType = parameterTypes[i++];

  for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("param: " + parameterType.getName());
        System.out.println("name : " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
  }
}

获取的参数注释是二维数组,按照参数声明的顺序,方法的每个参数对应一个数组(注解的集合)

Field Annotations

Field field = ... //obtain field object
Annotation[] annotations = field.getDeclaredAnnotations();
Annotation annotation = field.getAnnotation(MyAnnotation.class);//精确的

for(Annotation annotation : annotations){
    if(annotation instanceof MyAnnotation){
        MyAnnotation myAnnotation = (MyAnnotation) annotation;
        System.out.println("name: " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }
}

if(field.isAnnotationPresent(MyAnnotation.class))
     return  field.getAnnotationMyAnnotation.class);

数组 Array

java.lang.reflect.Array
java.util.Arrays是Java集合框架中的一部分,提供数组的排序,查找,复制等功能。

//创建
int[] intArray = (int[]) Array.newInstance(int.class, 3);

//访问数组
get(Object array, int index)
getBoolean(Object array, int index)

//设定数组
set(Object array, int index, Object value)
setBoolean(Object array, int index, boolean z)

//获取数组元素的类型
Class.getComponentType() 

泛型 Generics

类型参数(type parameters),类型擦除(erased),替换为限定类型
类型变量限定<T extends Comparable & Serializable>
通配符类型 public static <T> void copy (List<? extends T> src, List<? super T> dest)
List<? extends Number> 从泛型对象读取数据
List<? super Long> 向泛型对象写入

Type接口,描述Java中的所有类型。
Class<T>类实现了该接口
子接口
GenericArrayType 数组类型
ParameterizedType 参数化类型
TypeVariable<D extends [GenericDeclaration]>
WildcardType 通配符类型

泛型方法的返回类型 Generic Method Return Types

Type returnType = method.getGenericReturnType();

if(returnType instanceof ParameterizedType){
    ParameterizedType type = (ParameterizedType) returnType;
    Type[] typeArguments = type.getActualTypeArguments(); //获取类型参数
    for(Type typeArgument : typeArguments){
        Class typeArgClass = (Class) typeArgument;
        System.out.println("typeArgClass = " + typeArgClass);
    }
}

泛型方法的参数类型 Generic Method Parameter Types

//setStringList(List<String> list){}
method = Myclass.class.getMethod("setStringList", List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();

for(Type genericParameterType : genericParameterTypes){
    if(genericParameterType instanceof ParameterizedType){
        ParameterizedType aType = (ParameterizedType) genericParameterType;
        Type[] parameterArgTypes = aType.getActualTypeArguments();
        for(Type parameterArgType : parameterArgTypes){
            Class parameterArgClass = (Class) parameterArgType;
            System.out.println("parameterArgClass = " + parameterArgClass);
        }
    }
}

泛型字段类型 Generic Field Types

Type genericFieldType = field.getGenericType();

if(genericFieldType instanceof ParameterizedType){
    ParameterizedType aType = (ParameterizedType) genericFieldType;
    Type[] fieldArgTypes = aType.getActualTypeArguments();
    for(Type fieldArgType : fieldArgTypes){
        Class fieldArgClass = (Class) fieldArgType;
        System.out.println("fieldArgClass = " + fieldArgClass);
    }
}

其他:还有动态代理 Dynamic Proxies机制

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容