簡體   English   中英

有沒有辦法通過 ByteBuddy 中的攔截器通過 MethodDescription 調用方法?

[英]Is there a way to invoke a method by MethodDescription from the interceptor in ByteBuddy?

我正在實現一個代理,它使加載的 class 隱式實現一個接口。 接口中的方法,由代理實現,以自定義的方式調用原始的 class 方法,標記有特殊的注釋。 但事實證明,在AgentBuilder.Transformer中加載的 class 仍然不存在。 然而,攔截器內的代碼是在實際加載 class 之后執行的。 因此攔截器中的代碼可以與 class 方法一起使用。 我可以使用MethodDescription對象調用這些方法嗎?

public class CustomTransformer implements AgentBuilder.Transformer {

    public static class InstantiateInterceptor {

        private final Collection<MethodDescription> methodDescription;

        InstantiateInterceptor(Collection<MethodDescription> methodDescription) {
            this.methodDescription = methodDescription;
        }

        public Object intercept(@This Object self) {
            //
            // Call method by descriptions somewhere here
            //
            return null;
        }
    }

    @Override
    public DynamicType.Builder<?> transform(
            DynamicType.Builder<?> builder,
            TypeDescription typeDescription,
            ClassLoader classLoader,
            JavaModule module) {

        try {

            List<MethodDescription> cacheableMethods =
                    typeDescription.getDeclaredMethods().stream()
                            .filter(t -> t.getDeclaredAnnotations()
                                    .isAnnotationPresent(EnhanceMarker.class))
                            .collect(Collectors.toList());

            return builder
                    .implement(HasField.class)
                    .define(HasField.class.getMethod("value"))
                    .intercept(MethodDelegation
                            .to(new InstantiateInterceptor(cacheableMethods)));
        } catch (NoSuchMethodException ex) {
            ex.printStackTrace();
        }

        return builder;
    }
}

我可能可以通過它的名字從@This object 得到這個方法。 但它需要參數類型列表,我只能得到ParameterDescription class 對象的列表,它不返回參數類型。

如果該方法在@This實例上可用,為什么不直接調用它而不進行反射? 或者這個方法是生成的? 在這種情況下,在接口中定義簽名,實現該接口並在該接口上讀取@This實例。

如果你想調用超級方法,你可以對一個由@Super注釋的實例執行相同的操作,其中 Byte Buddy 會創建一個適當的代理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM