java反射初探

package com.javareflect.base.demo;

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

public class InvokerTester {

public int add(int m, int n) {
return m + n;
}

public String echo(String message) {
return "hello" + message;
}

private String sayHello(String str) {
return "hello"+str;
}

public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException,
SecurityException, IllegalArgumentException, InvocationTargetException {
Class<?> classType = InvokerTester.class;//获取类对象
Object invokerTester = classType.newInstance();//获取类的实例
Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class });
Object result = addMethod.invoke(invokerTester, new Object[] { 1, 2 });
System.out.println(result);
Method echoMe = classType.getMethod("echo", new Class[]{String.class});
Object r2 = echoMe.invoke(invokerTester, new Object[]{"ffffffffff"});
System.out.println(r2);

Method sayMe = classType.getDeclaredMethod("sayHello", new Class[]{String.class});
sayMe.setAccessible(true);
String s = (String)sayMe.invoke(invokerTester, new Object[]{"ggggggg"});
System.out.println(s);
}

}
[size=large][size=medium]
[/size][/size]

猜你喜欢

转载自hehefan.iteye.com/blog/2306988