package daoannotation; import java.lang.annotation.AnnotationFormatError; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DaoProxyFactory { @SuppressWarnings("unchecked") public static T newRoleDaoProxy(Class dao) { Implement implAnnotation = dao.getAnnotation(Implement.class); if (implAnnotation == null) { throw new AnnotationFormatError("this is no annotation for this interface: " + dao.getSimpleName().toString()); } BaseDao implClass = null; try { implClass = implAnnotation.value().newInstance(); } catch (Exception e) { throw new RuntimeException("this interface cannot be instanized!", e); } return (T) Proxy.newProxyInstance( DaoProxyFactory.class.getClassLoader(), new Class[] { dao }, new RoleInovationHandler(implClass)); } private static final class RoleInovationHandler implements InvocationHandler { private BaseDao target; public RoleInovationHandler(BaseDao target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Permission permitAnnotation = method.getAnnotation(Permission.class); outter: if (permitAnnotation != null) { Role currentRole = RoleContext.INSTANCE.getCurrentRole(); for (Role role : permitAnnotation.value()) { if (role.equals(currentRole)) { break outter; } } throw new SecurityException("user is not allowed to this operation!"); } return method.invoke(target, args); } } public static void main(String[] args) { UserDao userDao = DaoProxyFactory.newRoleDaoProxy(UserDao.class); userDao.save(); userDao.delete(); //userDao.query(); } }