Method类:它的实例对象代表某个类中的一个成员方法
代码实例:用反射调用String类的charAt方法
package com.reflection.method;
import java.lang.reflect.Method;
public class ReflectionGetMethod {
public static void main(String[] args) {
/**
* Method类,用反射获得一个对象的方法,并且调用该方法,用String类演示,调用charAt() 方法
* new String.charAt(2) 用反射实现
*/
String str = "abcdefg";
Class cls = str.getClass();
try {
//获取String类中的charAt(int index)方法对象 .getMethod获取单个具体的方法
Method methodCharAt = cls.getMethod("charAt", int.class); //第一个参数为对象的方法名,第二参数为该方法的参数类型
System.out.println(methodCharAt.invoke(str, 2)); //方法对象.invoke方法,表示调用该方对象对象的底层方法
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
|