被代理对象的接口
1 public interface IScoreService { 2 public void addScore(String s,String s1); 3 }
被代理的对象的实现
1 public class ScoreServiceImpl implements IScoreService{ 2 int score = 0; 3 public List<Integer> sList = new ArrayList<Integer>(); 4 5 public void addScore(String s,String s1){ 6 System.out.println(score+=3); 7 sList.add(score); 8 } 9 }
代理类
1 public class LogHandler implements InvocationHandler { 2 3 private Object targetObject; 4 5 public Object createProxy(Object targetObject){ 6 this.targetObject = targetObject; 7 return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), 8 targetObject.getClass().getInterfaces(), 9 this); 10 } 11 12 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 13 14 Object obj = null; 15 try { 16 beforeLog(); 17 obj = method.invoke(targetObject, args); 18 afterLog(); 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 23 24 return obj; 25 } 26 27 private void beforeLog(){ 28 System.out.println("在之前调用"); 29 } 30 31 private void afterLog(){ 32 System.out.println("在之后调用"); 33 } 34 35 }
测试类
1 public class TestHandler{ 2 public static void main(String [] args){ 3 IScoreService servcie = (IScoreService)logHandler.createProxy(new ScoreServiceImpl()); 4 servcie.addScore("",""); 5 } 6 }
时间: 2024-10-05 17:16:40