java.lang.Class.getDeclaredMethod()方法

来源:互联网 发布:域名交易市场 编辑:程序博客网 时间:2024/06/16 21:05

java.lang.Class.getDeclaredMethod()方法

java.lang.Class.getDeclaredMethod()方法用法实例教程 - 方法返回一个Method对象,它反映此Class对象所表示的类或接口的指定已声明方法。

描述
java.lang.Class.getDeclaredMethod()方法返回一个Method对象,它反映此Class对象所表示的类或接口的指定已声明方法。name参数是一个字符串,指定所需的方法的简单名称,parameterTypes参数是一个数组的Class对象识别方法的形参类型,在声明的顺序

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

public Method getDeclaredMethod(String name, Class… parameterTypes) throws NoSuchMethodException, SecurityException
参数
name – 方法的名称

parameterTypes – 参数数组

返回值
匹配指定名称和参数的类的方法,此方法返回的Method对象

异常
NoSuchMethodException – 如果匹配方法未找到

NullPointerException – 如果name 为 null.

SecurityException – If a security manager, s, is present.

实例
下面的例子说明了如何使用java.lang.Class.getDeclaredMethod()方法

package com.redsun;import java.lang.reflect.*;public class TestDemo {   public static void main(String[] args) {     TestDemo cls = new TestDemo();     Class c = cls.getClass();     try {                  // parameter type is null        Method m = c.getDeclaredMethod("say", null);        System.out.println("method = " + m.toString());         // method Integer        Class[] cArg = new Class[1];        cArg[0] = Integer.class;        Method lMethod = c.getDeclaredMethod("say", cArg);        System.out.println("method = " + lMethod.toString());     }     catch(NoSuchMethodException e) {        System.out.println(e.toString());     }   }   private String say() {      return "hello,world!";   }   public void say(String str) {      this.str = str;   }   public String str = "hello,china!";} 

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

method = private java.lang.Integer TestDemo.say()
method = public void TestDemo.say(java.lang.String)

0 0
原创粉丝点击