目录
- 学习内容
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.