1. Java 反射API的第一个主要作用是获取程序在运行时刻的内部结构。这对于程序的检查工具和调试器来说,是非常实用的功能。只需要短短的十几行代码,就可以遍历出来一个Java类的内部结构,包括其中的构造方法、声明的域和定义的方法等。这不得不说是一个很强大的能力。只要有了java.lang.Class类 的对象,就可以通过其中的方法来获取到该类中的构造方法、域和方法。对应的方法分别是getConstructor、getField和getMethod。这三个方法还有相应的getDeclaredXXX版本,区别在于getDeclaredXXX版本的方法只会获取该类自身所声明的元素,而不会考虑继承下来的。Constructor、Field和Method这三个类分别表示类中的构造方法、域和方法。这些类中的方法可以获取到所对应结构的元数据。
2.待测试类
3.测试方法
2.待测试类
- packagecom.home.action.test.mode.reflection;
- importjava.util.Map;
- publicclassCounter{
- publicintcount;
- publicMap<String,Object>map;
- publicCounter(intcount){
- this.count=count;
- }
- publicvoidincrease(intstep){
- count=count+step;
- System.out.println("count:"+count);
- }
- }
package com.home.action.test.mode.reflection;
import java.util.Map;
public class Counter {
public int count ;
public Map<String, Object> map;
public Counter(int count) {
this.count = count;
}
public void increase(int step) {
count = count + step;
System.out.println("count: "+count);
}
}
3.测试方法
- packagecom.home.action.test.mode.reflection;
- importjava.lang.reflect.Constructor;
- importjava.lang.reflect.Field;
- importjava.lang.reflect.InvocationTargetException;
- importjava.lang.reflect.Method;
- importjava.lang.reflect.ParameterizedType;
- importjava.lang.reflect.Type;
- /**
- *测试基本类的反射
- *@authorli
- */
- publicclassTest{
- @SuppressWarnings("rawtypes")
- publicstaticvoidmain(String[]args){
- try{
- //构造函数
- Constructor<Counter>contructor=Counter.class.getConstructor(int.class);
- System.out.println("contructorName:"+contructor.getName());
- Countercounter=contructor.newInstance(10);
- counter.increase(10);
- //基本方法
- Method[]methods=Counter.class.getMethods();
- for(Methodmethod:methods){
- System.out.println("method:"+method.getName());
- }
- Methodmethod=Counter.class.getMethod("increase",int.class);
- method.invoke(counter,6);
- //属性值
- Field[]fields=Counter.class.getFields();
- for(Fieldfield:fields){
- System.out.println("fieldName:"+field.getName());
- }
- //count类型要设置public否则获取不到,提示异常信息
- Fieldfield=Counter.class.getField("count");
- System.out.println("countField:"+field.getName());
- //处理泛型
- FieldmapField=Counter.class.getDeclaredField("map");
- Typetype=mapField.getGenericType();
- System.out.println("mapType:"+type.toString());
- if(typeinstanceofParameterizedType){
- ParameterizedTypeparamerizedType=(ParameterizedType)type;
- Type[]actualTypes=paramerizedType.getActualTypeArguments();
- for(Typet:actualTypes){
- if(tinstanceofClass){
- Classclz=(Class)t;
- System.out.println("classType:"+clz.getName());
- }
- }
- }
- }catch(SecurityExceptione){
- e.printStackTrace();
- }catch(NoSuchMethodExceptione){
- e.printStackTrace();
- }catch(IllegalArgumentExceptione){
- e.printStackTrace();
- }catch(InstantiationExceptione){
- e.printStackTrace();
- }catch(IllegalAccessExceptione){
- e.printStackTrace();
- }catch(InvocationTargetExceptione){
- e.printStackTrace();
- }catch(NoSuchFieldExceptione){
- e.printStackTrace();
- }
- }
- }