JavaSE:反射机制 - Method类

反射机制 - Method类

1.  基本概念

    java.lang.reflect.Method类:用于描述获取到的单个成员方法信息

 

2.  Class类中,有关Method的常用方法

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

获取该Class对象表示类中名字为name

参数为parameterTypes的指定公共成员方法

Method[] getMethods() 用于获取该Class对象表示类中所有公共成员方法

 

3.  Method类的常用方法

Object invoke(Object obj, Object... args) 使用对象obj来调用此Method对象所表示的成员方法,实参传递args
int getModifiers() 获取方法的访问修饰符
Class<?> getReturnType() 获取方法的返回值类型
String getName() 获取方法的名称
Class<?>[] getParameterTypes() 获取方法所有参数的类型
Class<?>[] getExceptionTypes() 获取方法的异常信息

4.  代码示例

 

    class PersonMethodTest {

      main() throws Exception {

      

        //  1.  使用原始方式,构造对象,并调用方法打印结果

        Person p1 = new Person("zhangfei",30);

        print("调用方法的返回值是:“ + p1.getName() );  //  zhangfei 

        

        //  2.  使用反射机制,构造对象,并调用方法,打印结果

        //  2.1  获取Class对象

        Class c1 = class.forName("com.lagou.task20.Person");

        //  2.2  根据Class对象,来获取对应的有参构造方法

        Constructor constructor = c1.getConstructor(String.class,int.class)

        //  2.3  使用有参构造方法构造对象,并记录

        Object object = constructor.newInstance("zhangfei",30);

        //  2.4  根据Class对象,来获取对应的成员方法

        Method method = c1.getMethod("getName");

        //  2.5  使用对象调用成员方法,进行打印

        //  表示使用object对象调用method表示的方法,也就是调用getName方法来获取姓名

        println("调用方法的返回值是:" + method.invoke(object) );  //  zhangfei

 

        //  3.  使用反射机制,来获取类中的所有成员方法,并打印

        Method[] methods = c1.getMethods();

        for (Method mt : methods) {

          print("成员方法的修饰符是:"  + mt.getModifiers() );

          print("成员方法的返回值类型是:" + mt.getReturnType() );

          print("成员方法的名称是:" + mt.getName() );

          

          System.out.println("成员方法形参列表的类型是:");
          Class<?>[] parameterTypes = mt.getParameterTypes();
          for (Class ct : parameterTypes) {
            System.out.print(ct + " ");
          }
          System.out.println();
          System.out.println("成员方法的异常类型列表是:");
          Class<?>[] exceptionTypes = mt.getExceptionTypes();
          for (Class ct: exceptionTypes) {
            System.out.print(ct + " ");
          }

        }

      }

    }

 

<1>

 

 

<2>  获取一个类中的所有的成员方法

 

posted @ 2021-06-16 13:18  Jasper2003  阅读(143)  评论(0编辑  收藏  举报