Method类

一、Method类

代表类中的一个方法的定义,一个Method由修饰符,返回值,方法名称,参数列表组合而成。

二、Method提供的方法

1、getName();获得方法名。

2、getModifiers();获得修饰符。

3、getReturnTypes();返回值类型。返回class

4、getParameterTypes();返回Class[],参数类型的数组。

5、invoke(Object obj,Object…args);

三、如何获得Method呢?

1、Class方法。

2、Method GetMethod(String name,Class<?>…args);

3、Method[] getMethod();获得所有的公共方法。

4、Method getDeclaredMethod(String name,Class…args);根据名称和参数获得对应的方法。

5、Method[] getDeclaredMethods();获得当前类中定义的所有方法。

例子:

//获得所有公共方法
		Method[] mt=c.getMethods();
		for(Method m:mt) {
			System.out.println(Modifier.toString(m.getModifiers())+"\t"+m.getReturnType().getSimpleName()+"\t"+m.getName());
			Class[] pt=m.getParameterTypes();
			for(Class p:pt) {
				System.out.println("\t\t"+p.getSimpleName());
			}
		}
		System.out.println("----------------------");
		//获得所有方法
		Method[] mt1=c.getDeclaredMethods();
		for(Method m:mt1) {
			System.out.println(m.getName());
		}
		System.out.println("----------------------");
		//获得指定方法
		Method mt2=c.getDeclaredMethod("priTest", String.class);
		mt2.setAccessible(true);
		book b=new book();
		mt2.invoke(b, "\t xixihah");
		System.out.println("----------------------");
		Method mt3=c.getDeclaredMethod("priTest");
		mt3.setAccessible(true);
		mt3.invoke(b);

原文:https://blog.csdn.net/a_helloworld_/article/details/78521710
版权声明:本文为博主原创文章,转载请附上博文链接!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值