📜  Java中的类 getMethod() 方法和示例

📅  最后修改于: 2022-05-13 01:55:34.277000             🧑  作者: Mango

Java中的类 getMethod() 方法和示例

Java.lang.Class类getMethod()方法用于获取该类指定参数类型的指定方法,即公共方法及其成员。该方法以Method对象的形式返回该类的指定方法。

句法:

public Method getMethod(String methodName, 
                    Class[] parameterType) 
       throws NoSuchMethodException, SecurityException

参数:此方法接受两个参数:

  • methodName是要获取的方法。
  • parameterType是指定方法的参数类型数组。

返回值:该方法以Method对象的形式返回该类的指定方法

异常此方法抛出:

  • 如果未找到具有指定名称的方法,则NoSuchMethodException
  • 如果名称为空,则出现NullPointerException
  • 如果存在安全管理器并且不满足安全条件,则出现 SecurityException。

    下面的程序演示了 getMethod() 方法。

    示例 1:

    // Java program to demonstrate getMethod() method
      
    import java.util.*;
      
    public class Test {
      
        public void func() {}
      
        public static void main(String[] args)
            throws ClassNotFoundException, NoSuchMethodException
        {
      
            // returns the Class object for this class
            Class myClass = Class.forName("Test");
      
            System.out.println("Class represented by myClass: "
                               + myClass.toString());
      
            String methodName = "func";
            Class[] parameterType = null;
      
            // Get the method of myClass
            // using getMethod() method
            System.out.println(
                methodName + " Method of myClass: "
                + myClass.getMethod(methodName, parameterType));
        }
    }
    
    输出:
    Class represented by myClass: class Test
    func Method of myClass: public void Test.func()
    

    示例 2:

    // Java program to demonstrate getMethod() method
      
    import java.util.*;
      
    class Main {
      
        public void func() {}
      
        public static void main(String[] args)
            throws ClassNotFoundException, NoSuchMethodException
        {
            // returns the Class object for this class
            Class myClass = Class.forName("Main");
      
            System.out.println("Class represented by myClass: "
                               + myClass.toString());
      
            String methodName = "func";
            Class[] parameterType = null;
      
            try {
                // Get the method of myClass
                // using getMethod() method
                System.out.println(
                    methodName + " Method of myClass: "
                    + myClass.getMethod(methodName, parameterType));
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    输出:
    Class represented by myClass: class Main
    java.lang.NoSuchMethodException: Main.func()
    

    参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getMethod-java.lang.String-java.lang.Class…-