JAVA AOP 动态代理 的例子

本文介绍了一个使用Java反射和动态代理实现的简单面向切面编程(AOP)案例。通过自定义`myAOP`类作为调用处理器,并对`student`类的方法调用前后增加额外的操作,展示了AOP的基本原理。
package myaop;
import java.util.*;
import java.lang.reflect.*;


interface person {
  String getName();
  int getID();
}


class student implements person{
private String name;
private int id;
student(){
System.out.println("student: student() called ");
name="nonmae";
id=0;
}
student(int mid, String name){
this.name=name;
this.id=mid;
}
public String getName(){
System.out.println("student: getName() called. Name= "+name);
return name;
}
public int getID() {
System.out.println("student: getID() called: id= "+id);
 return id;
 }
}
class actions {
public void BeforeActions(){
System.out.println("actions: BeforeActions() called ");
}
public void AfterActions(){
System.out.println("actions: AfterActions() called ");
}
}


class myAOP implements InvocationHandler{
public Object proxyee;
public void setTarget(Object target){
proxyee=target;
}

public Object invoke(Object myproxy, Method method, Object[] args){
System.out.println("myAOP:invoke() enters");
actions maction = new actions();
maction.BeforeActions();


Object result=null;
try {
result=method.invoke(proxyee,args);
}

catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

maction.AfterActions();
  return result;
}
}


public class AOPTrial {
public static void main(String[] args) {
// TODO Auto-generated method stub
person sta = new student(1,"jac2k");
myAOP handler = new myAOP();
handler.setTarget(sta);
Object mystu=Proxy.newProxyInstance(sta.getClass().getClassLoader(), 
sta.getClass().getInterfaces(),handler);
/*
* student: getID() called: id= 1
* student: getName() called. Name= jac2k
*/
((person)sta).getID();
((person)sta).getName();

/*
myAOP:invoke() enters
actions: BeforeActions() called 
student: getID() called: id= 1
actions: AfterActions() called 
myAOP:invoke() enters
actions: BeforeActions() called 
student: getName() called. Name= jac2k
actions: AfterActions() called 
*/
//here can't covert to student 
((person)mystu).getID();
((person)mystu).getName();


}


}


输出结果

student: getID() called: id= 1
student: getName() called. Name= jac2k
myAOP:invoke() enters
actions: BeforeActions() called 
student: getID() called: id= 1
actions: AfterActions() called 
myAOP:invoke() enters
actions: BeforeActions() called 
student: getName() called. Name= jac2k
actions: AfterActions() called 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值