Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Annotation that is only valid for a classes implementing a specific interface?

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

The purpose of the annotation is to allow a manager to know that it needs to add an instance of that class to its set of managed objects. So if there's no way to add that restriction at compile time what would be the best pattern to deal with this at runtime?

Background: At present I have an application that allows users to perform a set of pre defined actions on a Strings[] that results in a single string output, the actions are grouped by scenario and I have an enum per scenario with those actions defined, and a single class that has a switch on these enums to call individual methods (all within that class), meaning that adding a single action involves changes to several areas in the code, and I want to increase it's maintainability by allowing a rookie developer to only need be aware of a single class they need to write that will add the action in to the right list and be available automatically.

The solution I have decided upon is to have an Action Interface that the developer will implement, and then add an annotation to register that Action with the desired scenario/scenarios, isolating any new changes to the creation of a single class.

like image 322
Link19 Avatar asked Oct 24 '12 08:10

Link19


1 Answers

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

On the other hand; if your interface only exists for that reason, you could just create the rule "all classes implementing this interface".

Of course, this is all assuming you have control over the Manager creating the instances.

like image 158
Joeri Hendrickx Avatar answered Nov 10 '22 10:11

Joeri Hendrickx