日期:2014-05-20 浏览次数:20836 次
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Ticmy {
public String before() default "123";
public String after() default "345";
}
interface Service {
public void mymethod();
public void mymethod2();
}
class ServiceImpl implements Service {
@Ticmy
public void mymethod() {
System.out.println("in mymethod");
}
@Ticmy(before="before mymethod2", after="after mymethod2")
public void mymethod2() {
System.out.println("in mymethod2");
}
private ServiceImpl() {/*直接new注解没有效果*/}
public static Service getInstance() {
//也可以使用其它方式
return (Service)Proxy.newProxyInstance(Service.class.getClassLoader(),
new Class[]{Service.class}, new TicmyInvocationHandler(new ServiceImpl()));
}
static class TicmyInvocationHandler implements InvocationHandler {
private Object delegation;
public TicmyInvocationHandler(Object delegation) {
this.delegation = delegation;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//这里只判断接口上的方法是否有注解
Method methodInImpl = delegation.getClass().getMethod(method.getName(), method.getParameterTypes());
Ticmy ticmy = methodInImpl.getAnnotation(Ticmy.class);
Object ret;
if(ticmy != null) {
//如果有注解
System.out.println(ticmy.before());
ret = method.invoke(delegation, args);
System.out.println(ticmy.after());
} else {
ret = method.invoke(delegation, args);
}
return ret;
}
}
}
public class MyAnnotation {
public static void main(String[] args) {
Service instance = ServiceImpl.getInstance();
instance.mymethod();
System.out.println("--------");
instance.mymethod2();
}
}