1 回答
TA贡献1848条经验 获得超10个赞
如果你想要的是批注方法,那么在没有AOP的情况下是可能的。
只需使用动态代理!interface
实现代理的基础是interfaceInvocationHandler
调用处理程序是由代理实例的调用处理程序实现的接口。
遵循代码内注释。
static class MyInterfaceProxy implements InvocationHandler {
private static final Map<String, Method> METHODS = new HashMap<>(16);
static {
// Scan each interface method for the specific annotation
// and save each compatible method
for (final Method m : IMyInterface.class.getDeclaredMethods()) {
if (m.getAnnotation(YourAnnotation.class) != null) {
METHODS.put(m.getName(), m);
}
}
}
private final IMyInterface toBeProxied;
private MyInterfaceProxy(final IMyInterface toBeProxied) {
// Accept the real implementation to be proxied
this.toBeProxied = toBeProxied;
}
@Override
public Object invoke(
final Object proxy,
final Method method,
final Object[] args) throws InvocationTargetException, IllegalAccessException {
// A method on MyInterface has been called!
// Check if we need to call it directly or if we need to
// execute something else before!
final Method found = METHODS.get(method.getName());
if (found != null) {
// The method exist in our to-be-proxied list
// Execute something and the call it
// ... some other things
System.out.println("Something else");
}
// Invoke original method
return method.invoke(toBeProxied, args);
}
}
要使用此实现,您需要一个要代理的对象的真实实例。InvocationHandler
假设您有一个用于实现的工厂MyInterface
MyInterface getMyInsterface() {
...
final MyInterface instance = ...
// Create the proxy and inject the real implementation
final IMyInterface proxy = (IMyInterface) Proxy.newProxyInstance(
MyInterfaceProxy.class.getClassLoader(),
new Class[] {IMyInterface.class},
new MyInterfaceProxy(instance) // Inject the real instance
);
// Return the proxy!
return proxy;
}
添加回答
举报