java反射简单记录

1. Java 反射API的第一个主要作用是获取程序在运行时刻的内部结构。这对于程序的检查工具和调试器来说,是非常实用的功能。只需要短短的十几行代码,就可以遍历出来一个Java类的内部结构,包括其中的构造方法、声明的域和定义的方法等。这不得不说是一个很强大的能力。只要有了java.lang.Class类 的对象,就可以通过其中的方法来获取到该类中的构造方法、域和方法。对应的方法分别是getConstructor、getField和getMethod。这三个方法还有相应的getDeclaredXXX版本,区别在于getDeclaredXXX版本的方法只会获取该类自身所声明的元素,而不会考虑继承下来的。Constructor、Field和Method这三个类分别表示类中的构造方法、域和方法。这些类中的方法可以获取到所对应结构的元数据。

2.待测试类

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.测试方法

package com.home.action.test.mode.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
* 测试基本类的反射
* @author li
*/
public class Test {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
try {
//构造函数
Constructor<Counter> contructor = Counter.class.getConstructor(int.class);
System.out.println("contructorName: "+contructor.getName());

Counter counter = contructor.newInstance(10);
counter.increase(10);

//基本方法
Method[] methods = Counter.class.getMethods();
for(Method method: methods) {
System.out.println("method: "+method.getName());
}

Method method = Counter.class.getMethod("increase", int.class);
method.invoke(counter, 6);

//属性值
Field[] fields = Counter.class.getFields();
for(Field field: fields) {
System.out.println("fieldName: "+field.getName());
}

//count类型要设置public 否则获取不到, 提示异常信息
Field field = Counter.class.getField("count");
System.out.println("countField: "+field.getName());

//处理泛型
Field mapField = Counter.class.getDeclaredField("map");
Type type = mapField.getGenericType();
System.out.println("mapType: "+ type.toString());

if(type instanceof ParameterizedType) {
ParameterizedType paramerizedType = (ParameterizedType)type;

Type[] actualTypes = paramerizedType.getActualTypeArguments();
for(Type t: actualTypes) {
if(t instanceof Class){
Class clz = (Class)t;
System.out.println("classType: "+ clz.getName());
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值