生活随笔
收集整理的這篇文章主要介紹了
关于反射的完整 练习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
做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 stubSystem.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("######################################");}
}
總結
以上是生活随笔為你收集整理的关于反射的完整 练习的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。