Method类及其用法

来源:互联网 发布:国外有什么直播软件 编辑:程序博客网 时间:2024/06/13 04:03

一、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);

原创粉丝点击