/**
*
*/
package de.tutorials;
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;
/**
* @author Tom
*/
public class DynamicProxyExample {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
IService service = (IService) Proxy.newProxyInstance(DynamicProxyExample.class.getClassLoader(),
new Class[] { IService.class }, new TargetAwareSecureMethodInvocationHandler<IService>(new Service()));
service.businessOperation();
System.out.println("########");
service.anotherBusinessOperation();
}
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
static @interface Secure {
}
static interface IService {
void businessOperation();
@Secure
void anotherBusinessOperation();
}
static class Service implements IService {
public void anotherBusinessOperation() {
System.out.println("anotherBusinessOperation");
}
public void businessOperation() {
System.out.println("businessOperation");
}
}
static class TargetAwareSecureMethodInvocationHandler<TTarget> implements InvocationHandler {
TTarget target;
/**
* @param target
*/
public TargetAwareSecureMethodInvocationHandler(TTarget target) {
super();
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.isAnnotationPresent(Secure.class)) {
checkAccess(method);
}
return method.invoke(getTarget(), args);
}
private void checkAccess(Method method) {
System.out.println("perform access check for: " + method);
}
/**
* @return the target
*/
public TTarget getTarget() {
return target;
}
/**
* @param target the target to set
*/
public void setTarget(TTarget target) {
this.target = target;
}
}
}