Java.lang.Class类 getMethod()方法有什么功能呢?
下文讲述Class类中的getMethod()方法的功能,如下所示:
通过方法名和参数信息,匹配出对象中的Method对象
getMethod()方法的示例分享
getMethod()方法的功能
java.lang.Class.getMethod(String name, Class<?>... parameterTypes)方法的功能通过方法名和参数信息,匹配出对象中的Method对象
注意事项:
此方法无法获取private修饰符修饰的方法
getMethod()方法的语法
语法
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException
参数
name:方法名称
parameterTypes:参数列表
返回值
根据方法名和参数信息匹配出Method对象
例:getMethod()方法的示例分享
package com.java.other;
import java.lang.reflect.Method;
import org.junit.Test;
public class other {
/**
* java265.com java.lang.Class 测试示例分享
*
*/
@Test
public void test() {
try {
Class c[] = new Class[] { int.class, float.class };
Method m2 = this.getClass().getMethod("testB", c);
System.out.println(m2);
Method m1 = this.getClass().getMethod("testA", c);
System.out.println(m1);
} catch (Exception e) {
System.out.println(e);
}
}
private String testA(int i, float j) {
return "";
}
public String testB(int i, float j) {
return "";
}
}
------运行以上代码,将输出以下信息-----
public java.lang.String com.java.other.other.testB(int,float)
java.lang.NoSuchMethodException: com.java.other.other.testA(int,float)
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


