当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.lang.Class.getMethod()用法及代码示例



描述

这个java.lang.Class.getMethod()返回一个 Method 对象,该对象反映了此 Class 对象表示的类或接口的指定公共成员方法。这name参数是一个字符串,指定所需方法的简单名称。

这个parameterTypes参数是一个 Class 对象的数组,这些对象按声明的顺序标识方法的形式参数类型。如果parameterTypes为空,则将其视为空数组。 .

声明

以下是声明java.lang.Class.getMethod()方法

public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

参数

  • name- 这是方法的名称。

  • parameterTypes- 这是参数列表。

返回值

此方法返回与指定名称和参数类型匹配的 Method 对象。

异常

  • NoSuchMethodException- 如果没有找到匹配的方法或者名称是 <init> 或 <clinit>。

  • NullPointerException- 如果名称为空

  • SecurityException− 如果存在安全管理器 s。

示例

下面的例子展示了 java.lang.Class.getMethod() 方法的用法。

package com.tutorialspoint;

import java.lang.reflect.*;

public class ClassDemo {

   public static void main(String[] args) {
    
      ClassDemo cls = new ClassDemo();
      Class c = cls.getClass();

      try {                
         // parameter type is null
         Method m = c.getMethod("show", null);
         System.out.println("method = " + m.toString());        
      } catch(NoSuchMethodException e) {
         System.out.println(e.toString());
      }
 
      try {
         // method Long
         Class[] cArg = new Class[1];
         cArg[0] = Long.class;
         Method lMethod = c.getMethod("showLong", cArg);
         System.out.println("method = " + lMethod.toString());
      } catch(NoSuchMethodException e) {
         System.out.println(e.toString());
      }
   }

   public Integer show() {
      return 1;
   }
    
   public void showLong(Long l) {
      this.l = l;
   }
   long l = 78655;
}

让我们编译并运行上面的程序,这将产生以下结果 -

method = public java.lang.Integer com.tutorialspoint.ClassDemo.show()
method = public void com.tutorialspoint.ClassDemo.showLong(java.lang.Long)

相关用法


注:本文由纯净天空筛选整理自 Java.lang.Class.getMethod() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。