生活随笔
收集整理的這篇文章主要介紹了
动态代理案例1:运用Proxy动态代理来增强方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
動態代理案例1:
/*要求:運用Proxy動態代理來增強方法
題目:
??? 1.定義接口Fruit,其中有addFruit方法
??? 2.定義實現類FruitImpl,實現Fruit接口
??? 3.定義測試類,利用動態代理類的方式,增強addFruit方法*/
1 import java.lang.reflect.Proxy;
2 import java.lang.reflect.InvocationHandler;
3 import java.lang.reflect.Method;
4 import java.lang.reflect.InvocationTargetException;
5
6 //接口
7 interface Fruit{
8 public abstract void addFruit();
9 }
10
11 //實現類
12 class FruitImpl
implements Fruit{
13 @Override
14 public void addFruit(){
15 System.out.println("
添加水果...");
16 }
17 }
18
19 //測試類---編寫代理,增強實現類中的方法
20 public class FruitDemo{
21 public static void main(String[] args){
22 //創建動態代理對象
23 Object f = Proxy.newProxyInstance(FruitImpl.
class.getClassLoader(), FruitImpl.
class.getInterfaces(),
24 new InvocationHandler(){
25 @Override
26 public Object invoke(Object Proxy, Method method, Object[] args){
27 System.out.println("
選擇水果.....................");
28 Object obj =
null;
29 try{
30 obj = method.invoke(
new FruitImpl(),args);
31 }
catch(IllegalAccessException | InvocationTargetException | IllegalArgumentException e){
32 e.printStackTrace();
33 }
34 System.out.println("
添加成功~~");
35 return obj;
36 }
37 }
38 );
39
40 //代理對象向下(接口)轉型
41 Fruit f1 = (Fruit) f;
42
43 //轉型后的對象執行原方法(已增強)
44 f1.addFruit();
45 }
46 }
47
轉載于:https://www.cnblogs.com/huguangqin/p/7137551.html
總結
以上是生活随笔為你收集整理的动态代理案例1:运用Proxy动态代理来增强方法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。