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

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

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

Java.lang.Class类getDeclaredMethod()方法用于获取该类指定参数类型的指定方法。该方法以Method对象的形式返回该类的指定方法。

句法:

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

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

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

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

异常此方法抛出:

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

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

    示例 1:

    // Java program to demonstrate
    // getDeclaredMethod() 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 getDeclaredMethod() method
            System.out.println(
                methodName + " Method of myClass: "
                + myClass.getDeclaredMethod(
                      methodName, parameterType));
        }
    }
    
    输出:
    Class represented by myClass: class Test
    func Method of myClass: public void Test.func()
    

    示例 2:

    // Java program to demonstrate
    // getDeclaredMethod() method
      
    import java.util.*;
      
    class Main {
      
        private 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 getDeclaredMethod() method
                System.out.println(
                    methodName + " Method of myClass: "
                    + myClass.getDeclaredMethod(
                          methodName, parameterType));
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    输出:
    Class represented by myClass: class Main
    func Method of myClass: private void Main.func()
    

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