JavaEE企业开发新技术3

目录

2.11  Method的基本操作-1

文字性概念描述

代码:

2.12 Method的基本操作-2

2.13 Method的基本操作-3

2.14 数组的反射操作-1

文字性概念:

代码:

2.15 数组的反射操作-2


  • 学习内容

2.11  Method的基本操作-1

文字性概念描述

Method类

Method用来表示类中的方法。通过Class对象的如下方法得到Method对象

Method getMethod(String name, Class<?>... parameterTypes

按名称得到某个特定的public方法(包括从父类或接口继承的方法)

Method[] getMethods()

得到public方法(包括从父类或接口继承的方法)

Methodl getDeclaredMethods()

得到所有的方法(不包括继承的方法)

Method getDeclaredMethod(String name, Class<?>...parameterlypes)

按名称得到某个特定的方法(不包括继承的方法)

得到某个方法对应的Method对象后,需要调用如下方法来在某个对象上执行该方法:

(1)invoke(Object obj,Object ...obj)方法用来调用Method所表示的方法。其中,第一个参数表示此方法作用于哪一个对象。

注意:如果调用的是个静态方法,那么invoke0方法中第一个参数用null表示。

代码:
public abstract class Test3 {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		Person p1=new Person();
		Class clazz1=p1.getClass();
		System.out.println(clazz1==Person.class);
		
		Person p=(Person)clazz1.getConstructor(Integer.class,String.class,String.class,int.class,String.class).newInstance(100,"小明","男",1,"O型血");
		
		Method[] methods=clazz1.getMethods();
		for(Method m:methods) {
			System.out.println("共有的方法名称是:"+m.getName());
		}
	}
}

总结:拿到了所有共有的方法,包括从父类继承的方法

Person类中添加缺省的方法

void init() {

System.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值