Java Annotation, which is valid only for classes that implement a specific interface?

I'm not sure if there is a way to do this, but I would like to have annotation for Classes, which is only valid for classes that implement a specific interface.

The purpose of the annotation is to let the manager know that he needs to add an instance of this class to his set of managed objects. So, if there is no way to add this restriction at compile time, what would be the best example to solve this problem at runtime?

Background: I currently have an application that allows users to perform a set of predefined actions in Strings [], resulting in one line output, the actions are grouped by script, and I have an enumeration for each script with the specified actions and one class , which has a switch in these enumerations for calling individual methods (all within this class), which means that adding one action includes changes in several areas of the code, and I want to increase its rem It’s suitable, allowing the beginner developer to keep in mind the one class that they need to write, which will add the action to the correct list and will be available automatically.

The solution I decided was to have an action interface that the developer would implement, and then add an annotation to register this action with the desired script / scripts, isolating any new changes when creating one class.

+4
source share
1 answer

You can use the marker interface , which is more or less a precursor to annotations when it comes to classes. If you define it to extend the interface you talked about, you can be sure that any class marked with it also implements your interface.

On the other hand; if your interface exists only for this reason, you can simply create the rule "all classes that implement this interface".

Of course, all this assumes that you are managing the instance manager.

+2
source

Source: https://habr.com/ru/post/1441761/


All Articles