做java的永远跳不过的一个坎就是反射,对反射的理解和利用 的能力 是一个天花板
package ft1;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface wt {
void show();
int add(int a, int b);
int show(int a, String s);
}
class wg implements wt {
public void show() {
}
public int add(int a, int b) {
return a + b;
}
public int show(int a, String s) {
// TODO Auto-generated method stub
System.out.println(s);
return a;
};
}
class proxy<T> implements InvocationHandler {
Object proxy;
public proxy(Object proxy) {
this.proxy = proxy;
}
T newProxyInstance(ClassLoader loader, Class<T>[] interfaces) {
return (T) Proxy.newProxyInstance(loader, interfaces, this);
}
public Object invoke(Object pp, Method method, Object[] args)
throws Throwable {
System.out.println(method.getName() + "函数代理执行开始");
System.out.println("...................");
System.out.println("函数名称是" + method.getName());
if (args != null) {
System.out.println("参数有" + args.length + "个");
for (int i = 0; i < args.length; i++) {
System.out.println("参数值" + args[i] + " 参数类型"
+ args[i].getClass().getName() + " ");
}
System.out.println();
} else {
System.out.println("没有参数");
}
System.out.println("返回值类型是" + method.getReturnType());
System.out.println("...................");
System.out.println("执行体xxx");
Object ob = method.invoke(proxy, args);
System.out.println("执行体xxx");
if (method.getReturnType().toString().equals("void"))
System.out.println(method.getName() + "没有返回值");
else {
System.out.println(method.getName() + "返回值是 " + ob);
}
System.out.println(method.getName() + "此函数代理执行完成\n");
return ob;
}
}
public class reflectTest {
public static void main(String[] args) {
wg g = new wg();
wt t = new proxy<wt>(g).newProxyInstance(
reflectTest.class.getClassLoader(), new Class[] { wt.class });
t.show();
System.out.println(t.add(1, 5));
System.out.println(t.show(1, "ttttttttttttt"));
System.out.println("######################################");
}
}