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;
}
添加回答
舉報