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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With