Reflection反射机制

import com.sun.jdi.InvocationException;

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

public class TestReflection {
public TestReflection(){
type = 1;
}
public TestReflection(Integer t){
type = t;
}
private Integer type;

public Integer plus(Integer num1,Integer num2) {
return num1 + num2;
}

public Integer minus(Integer num1,Integer num2) {
return num1 - num2;
}

public static void main(String[] args) throws ClassNotFoundException,NoSuchMethodException,InstantiationException,IllegalAccessException, InvocationTargetException {
//根据类全限定名称获取class类型
Class myTest = Class.forName("TestReflection");
System.out.println(myTest.getName());
//遍历构造函数
Constructor[] constructors = myTest.getConstructors();
for(Constructor con : constructors){
System.out.println(con.toString());
}
//遍历所有方法
Method[] methods = myTest.getDeclaredMethods();
for(Method method:methods){
System.out.println(method.toString());
}
//遍历所有字段
Field[] fields = myTest.getDeclaredFields();
for(Field field : fields){
System.out.println("字段:"+field.getName());
}
//实例化对象,执行方法
Object obj = myTest.getConstructor().newInstance();
Method plus1 = myTest.getDeclaredMethod("plus", Integer.class, Integer.class);
Method minus1 = myTest.getDeclaredMethod("minus", Integer.class, Integer.class);
Object plusResult = plus1.invoke(obj,5,3);
System.out.println(plusResult);

Object minsResult = minus1.invoke(obj,6,2);
System.out.println(minsResult);

}

}


转载于:https://www.cnblogs.com/TestMa/p/10636559.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值