Как создать bytebuddy агент, который перехватывает установщик поля из аннотированного поля? - PullRequest
1 голос
/ 23 октября 2019

То, что я пытаюсь сделать, это в основном сопоставить поле класса с аннотацией, и они перехватывают получатель и установщик поля.

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

Хотя я мог сопоставить имя поля с сигнатурой метода, но мне не повезло.

1 Ответ

1 голос
/ 24 октября 2019

Я предполагаю, что Foo имеет геттер и сеттер для Blah?

В этом случае я рекомендую пользовательскую реализацию ElementMatcher, такую ​​как:

class FieldMatcher implements ElementMatcher<MethodDescription> {
  @Override
  public boolean matches(MethodDescription target) {
    String fieldName;
    if (target.getName().startsWith("set") || target.getName().startsWith("get")) {
      fieldName = target.substring(3, 4).toLowerCase() + target.substring(4);
    } else if (target.getName().startsWith("is")) {
      fieldName = target.substring(2, 3).toLowerCase() + target.substring(3);
    } else {
      return false;
    }
    target.getDeclaringType()
      .getDeclaredFields()
      .filter(named)
      .getOnly()
      .getDeclaredAnnotations()
      .isAnnotationPresent(Sensitive.class);
  }
}

Thismatcher проверяет, является ли метод геттером или сеттером, находит соответствующее поле и проверяет наличие в нем аннотации.

...