动态代理类及自动实现方法

package com.fanShe;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
动态代理类及自动实现方法 * @param args */ interface Dog{ void info(); void run(); } class GunDog implements Dog{ public void info(){ System.out.println("我是一只猎狗"); } public void run() { System.out.println("我奔跑迅速"); } } class DogUtil{ public void method1(){ System.out.println("=====模拟第一个方法"); } public void method2(){ System.out.println("===模拟第二个方法"); } } //MyProxyFactory自动执行的方法invoke() class MyInvokationHandler implements InvocationHandler{ private Object target; public void setTarget(Object target){ this.target=target; } public Object invoke(Object proxy,Method method,Object[] args){ DogUtil du=new DogUtil(); du.method1(); Object result=null; try { //实现了 接口的子类中的所有方法 result = method.invoke(target, args); du.method2(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //这里的return 可以是null return result; } } //一个有把接口转变成 一个类的实例的 工厂 public class MyProxyFactory { public static Object getProxy(Object target){ MyInvokationHandler handler=new MyInvokationHandler(); handler.setTarget(target); return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler); } public static void main(String[] args) { // TODO Auto-generated method stub Dog target=new GunDog(); Dog dog=(Dog)MyProxyFactory.getProxy(target); dog.info(); dog.run(); } }
原文地址:https://www.cnblogs.com/shaoshao/p/3113801.html