如何创建一个 bytebuddy 代理来拦截带注释字段的字段设置器?

我想做的基本上是将类的字段与注释相匹配,并拦截该字段的 getter 和 setter。


 public class Foo {


    @Sensitive

    private String Blah;

这是我的代理的代码:


    private static AgentBuilder createAgent() {

        return new AgentBuilder

                .Default()

                .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)

                .type(ElementMatchers.is(FieldTypeMatcher.class).and(ElementMatchers.isAnnotatedWith(Foo.class)))

                .transform(((builder, typeDescription, classLoader, module) ->

                        builder

                        .method(method -> method.getActualName().contains(typeDescription.getActualName()))

                        .intercept(Advice.to(Interceptor.class))

                ));

    }

我虽然可以将字段的名称与方法的签名相匹配,但我没有运气。


不负相思意
浏览 54回答 1
1回答

繁花如伊

我假设Foo有一个 getter 和 setter Blah?在这种情况下,我建议使用自定义ElementMatcher实现,例如:class FieldMatcher implements ElementMatcher<MethodDescription> {&nbsp; @Override&nbsp; public boolean matches(MethodDescription target) {&nbsp; &nbsp; String fieldName;&nbsp; &nbsp; if (target.getName().startsWith("set") || target.getName().startsWith("get")) {&nbsp; &nbsp; &nbsp; fieldName = target.substring(3, 4).toLowerCase() + target.substring(4);&nbsp; &nbsp; } else if (target.getName().startsWith("is")) {&nbsp; &nbsp; &nbsp; fieldName = target.substring(2, 3).toLowerCase() + target.substring(3);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; target.getDeclaringType()&nbsp; &nbsp; &nbsp; .getDeclaredFields()&nbsp; &nbsp; &nbsp; .filter(named)&nbsp; &nbsp; &nbsp; .getOnly()&nbsp; &nbsp; &nbsp; .getDeclaredAnnotations()&nbsp; &nbsp; &nbsp; .isAnnotationPresent(Sensitive.class);&nbsp; }}该匹配器检查方法是否是 getter 或 setter,找到相应的字段并检查其上是否存在注释。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java