Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to a method through annotation

Tags:

java

Recently I've thought about an issue where you have a method that does some sort of action but it should not be called directly but rather through another method that properly handles it.

So what I've been thinking to do is create an annotation that will have inside it the method to use instead, I.E:

 @NonDirectUsage(direct=MyClass.directMethod);

It would have to be similar to comments where you can link a reference, however, I want to use it that way so it could be used further through runtime and so on.

Example in a live code would be something like:

List<Integer> myList = new ArrayList<>();

@Override
@NonDirectUsage(direct=addToList)
public void add(T t) {
    super.add(t);
}

public void addToList(Integer i) {
   System.out.println("added integer properly: "+i);
   add(i);
}

Is there any way of doing so?

like image 244
Tyrant Ist Avatar asked Nov 07 '22 18:11

Tyrant Ist


1 Answers

If you are using Spring, you could use AOP

e.g., your annotation would look something like:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface NonDirectUsage {
}

Then you define an Aspect

@Aspect
public class NonDirectUsageAspect{

    @Around("@annotation(NonDirectUsage)")
    public Object addToList(ProceedingJoinPoint joinPoint) throws Throwable {
       System.out.println("added integer properly: ");
       return null;
   }
}

do not forget to configure your code to handle aspects.

@Configuration  
@EnableAspectJAutoProxy
public class NoDirectUsageConfig {}

I think you can do something similar if you are using JakartaEE.

like image 143
fan Avatar answered Nov 14 '22 22:11

fan