Skip to content
Advertisement

Create custom method level annotation only available to specific return types [AOP]

I want to create an annotation which is only available to a specific type of return values.

For example this is my annotation.

JavaScript

I also have an interface:

JavaScript

An example class that implements my interface:

JavaScript

So after these, I want to configure my annotation in a way that it won’t even compile if the return type is not implementing MyInterface.

In this case, I expect this to compile fine:

JavaScript

And this to not compile:

JavaScript

I wonder if this is possible in any way. Sure I can check if the parameters implements this interface in my Aspect class but it would be better to have this kind of protection in my library in order to prevent misuse of any annotation.

Advertisement

Answer

Helper classer:

These are directly from your example, just with package names and imports.

JavaScript
JavaScript
JavaScript

Class which should not compile:

This class has some annotated and some non-annotated methods. One annotated method does not return MyInterface or any of its implementing classes. The goal is to fail compilation.

JavaScript

Convention-checking aspect (native AspectJ syntax):

JavaScript

This aspect checks for

  • all method executions
  • where the method has @MyAnnotation
  • but where the return type is different from MyInterface or any subtype or implementing class.

This is what the result looks like in Eclipse:

Eclipse: compilation error

Of course the compilation error is just the same if you compile from command line or via AspectJ Maven plugin or similar.

If you do not like native syntax (I prefer it but for some incomprehensible reason other people seem to prefer @AspectJ style):

Convention-checking aspect (annotation-based @AspectJ syntax):

JavaScript

See also my related answers here:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement