方法的反射

package ss;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * 方法的反射
 * @author Administrator
 *
 */
public class MethodInvoke {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
A a = new A();
//获取A类的类类型
Class c = a.getClass();
//
try {
//可以是个数组,也可以直接是多个参数
//获取到方法对象,用方法进行反射操作
Method m = c.getMethod("print", new Class[]{int.class,int.class});
// 一般我们是这样来调用到print方法;
// a.print(1, 2);
//这里的a对象操作print方法对象
//反过来换成m方法对象("print")操作a这个对象
//如果没有返回值返回Null,有返回值返回具体的返回值
// Object o = m.invoke(a, 2,2);
Object o = m.invoke(a, new Object[]{2,2});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
Method m1 = c.getMethod("print", String.class,String.class);
String s = (String) m1.invoke(a, "hello","word");
}
}
class A{
public void print(int a,int b){
System.out.println(a+b);
}
public void print(String a,String b){
System.out.println(a.toUpperCase()+b.toLowerCase());
}
}

猜你喜欢

转载自blog.csdn.net/fristname1/article/details/77995982
今日推荐