反射

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机制

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容