Search code examples
javaannotationsclassloadersuperclass

Java: Loading dynamic class annotation from supertype


Well guys; Here's my problem: I currently have a class extending another that will have a gameinfo.class annotation on each class (Is there a way I can enforce this with the compiler?)

Ideally I'd like to call the following in the type it is extending:

 @GameInfo(name = "Default Minigame", aliases = {"DM"}, pvp = false, authors = {"Tom"},
gameTime = 65, description = "desc")
public class DefaultMinigame extends Minigame {

    public DefaultMinigame(Plugin p) {
        super(p, DefaultMinigame.class.getAnnotation(GameInfo.class));
    }

I'd rather not have to call the above in each class and instead call it in Minigame.class How would I do this without calling "this" (Due to super type not being initialized)

Thanks for your time! (And sorry if what I'm saying isn't the most comprehensible of questions)


Solution

  • You can not enforce that a subclass has an annotation. If that is important to you, you might use the template method pattern instead.

    But if you need to use annotations, you can read the subclass annotation with

    class Minigame {
        protected Minigame() {
            GameInfo info = getClass().getAnnotation(GameInfo.class);
        }
    }