7

i'm working on a spring project and i want to make annotation.

I need something like the description below :

@CustomAnnotation("b")
public int a(int value) {
  return value;
}

public int b(int value) {
  return value + 1 ;
}

--------------------------

Execute :

a(1) // should return '2'  
1
  • @grape_mao I have a complex treatment at runtime this is just a simple example to describe it, i want method A call be automatically method B and method B should set value of method A Commented Oct 10, 2018 at 9:56

1 Answer 1

16

You can use Aspect. For example, you have following annotation

@Target(METHOD)
@Retention(RUNTIME)
public @interface Delegate {
  String value(); // this is the target method name
}

Then add the aspect component into your spring context

@Aspect // indicate the component is used for aspect
@Component
public class DelegateAspect {
  @Around(value = "@annotation(anno)", argNames = "jp, anno") // aspect method who have the annotation @Delegate
  public Object handle(ProceedingJoinPoint joinPoint, Delegate delegate) throws Exception {
    Object obj = joinPoint.getThis(); // get the object
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); // get the origin method
    Method target = obj.getClass().getMethod(delegate.value(), method.getParameterTypes()); // get the delegate method
    return target.invoke(obj, joinPoint.getArgs()); // invoke the delegate method
  }
}

Now you can use @Delegate to delegate methods

@Component
public class DelegateBean {

  @Delegate("b")
  public void a(int i) {
    System.out.println("a: " + i);
  }

  public void b(int i) {
    System.out.println("b: " + i);
  }
}

Let's test

@Inject
public void init(DelegateBean a) {
  a.a(1);
  a.b(1);
}

Output is

b: 1
b: 1
2
  • @Denoxus can you please explain @Around(value = "@annotation(anno)", argNames = "jp, anno")? I don't quite understand what's @annotation(anno) and jp, anno
    – iam.Carrot
    Commented Apr 19, 2019 at 7:13
  • argNames = "jp, anno" means we named the methods' params as jp and anno. @annotation means we aspect methods with some annotation. while anno's type is Delegate, it will match methods with @Delegate. You can refer to AspectJ documents to get more details.
    – Dean Xu
    Commented Apr 22, 2019 at 1:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.