Java 在注释另一个方法之前调用该方法

Java 在注释另一个方法之前调用该方法,java,reflection,annotations,Java,Reflection,Annotations,我试图通过使用注释将功能添加到接口方法签名中 其思想是在每个带注释的方法之前调用另一些方法 例如,如果我有此方法签名: public interface IMyInterface{ @Entity(visibileName = "Name") public TextField getName(); } 我需要调用一个方法,在这个方法之前、之后打印字符串名称。 另外,如果他们有任何方法可以在运行时定义此方法的功能 我也乐于接受结构变化。如果您想要的是注释接口方法,那么在没有AO

我试图通过使用注释将功能添加到接口方法签名中

其思想是在每个带注释的方法之前调用另一些方法

例如,如果我有此方法签名:

public interface IMyInterface{

    @Entity(visibileName = "Name")
    public TextField getName();
}
我需要调用一个方法,在这个方法之前、之后打印字符串名称。 另外,如果他们有任何方法可以在运行时定义此方法的功能


我也乐于接受结构变化。

如果您想要的是注释
接口
方法,那么在没有AOP的情况下是可能的。
只需使用动态代理

实现代理的基本
接口是
InvocationHandler

InvocationHandler是由调用实现的接口 代理实例的处理程序


跟随代码注释

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);
    }
}

我不确定您尝试完成的所有工作是否都可以通过这种方式完成,但是您可以看看AOPProxy.newProxyInstance,您能给我这个方法的完整实现吗?这个类的完整限定名是什么,jar文件是什么?@AliTaha它是JDK中的标准方法。已经完成了!
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;
}