亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在批注另一個方法之前調用方法

在批注另一個方法之前調用方法

慕勒3428872 2022-08-03 15:15:09
我正在嘗試通過使用注釋將功能添加到接口方法簽名中。這個想法是為每個帶注釋的方法調用一些其他方法。例如,如果我有此方法簽名:public interface IMyInterface{    @Entity(visibileName = "Name")    public TextField getName();}我需要調用一個方法,該方法在此方法之前,之后打印字符串名稱。如果有任何方法可以在運行時定義此方法的功能,也可以。我也對結構性變化持開放態度。
查看完整描述

1 回答

?
慕桂英546537

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;

}


查看完整回答
反對 回復 2022-08-03
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號