java 反射 构造_java - 反射 - 方法,构造方法

packagereflect;importjava.lang.annotation.Annotation;importjava.lang.reflect.Constructor;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;public classMethodTest {public static voidmain(String[] args){try{

System.out.println("-------------------------------------获取类的方法--------------------------------------------------");//通过方法名字, 参数类型的类 (因为方法有重构,名字可能相同)

Method m1 = TestClass.class.getMethod("methodTest", String.class, int.class);

Method m2= TestClass.class.getMethod("methodTest");

System.out.println(m1.getName());//返回方法名,getName()的返回值为String类型//methodTest

System.out.println(m1.getReturnType()); //返回返回值的类型 返回值为Class类型//int

System.out.println(m1.getModifiers()); //用数字表示方法的修饰符,相加后返回,int类型返回值//1 因为是public

Class[] cArr_m1 = m1.getParameterTypes(); //返回参数类型的class数组, Class类型返回值

for(Class c: cArr_m1){

System.out.println(c.getName());

}//java.lang.String//int

Class[] cArr2_m1 = m1.getExceptionTypes(); //返回抛出异常的类型的数组

Annotation[] a_m1 = m1.getAnnotations(); //返回注解数组

System.out.println("-------------------------------------使用类的方法--------------------------------------------------");

TestClass tc1= newTestClass();//不带参数的构造方法

int i = (int)m1.invoke(tc1,"name",111);//Method.invoke( 对象,参数1,参数2...参数n ); 有返回值的可以正常接收//带参数的普通方法

System.out.println(i);//1

System.out.println("-------------------------------------获取类的私有方法,继承自父类的方法--------------------------------------------------");

TestClass tc3= newTestClass();//不带参数的构造方法

Method m3 = TestClass.class.getMethod("toString"); //所有类默认继承Object,toString是Object中的方法

System.out.println(m3.invoke(tc3));//reflect.TestClass@7e0babb1 执行成功,说明取到了父类方法 引用变量的toString是 包名.类名@hashCode//Method m4 = TestClass.class.getMethod("privateTest");//会报错,不能取到private

Method m4 = TestClass.class.getDeclaredMethod("privateTest"); //和取属性的方法类似

m4.setAccessible(true);//操作私有方法要先给权限,和属性一样

m4.invoke(tc3);//私有的普通方法

}catch(NoSuchMethodException e) {

e.printStackTrace();

}catch(IllegalAccessException e) {

e.printStackTrace();

}catch(InvocationTargetException e) {

e.printStackTrace();

}

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值