Reputation: 645
I am trying to get an annotation of a child class within the constructor of an abstract parent.
public abstract class Skill {
private String identifier;
public Skill(){
identifier = getClass().getAnnotation(SerializableAs.class).value();
}
...
}
And the child looks like this:
@SerializableAs("TestSkill")
public class TestSkill extends Skill { ... }
Obviously the code above returns an NPE, because getAnnotation returns null for Skill, but is there a way to get the annotation from the child?
Because of the way how SerializableAs is involved in other fundamental parts of the system and how I create a new instance of TestSkill (via dynamic jar loading/reflection), I would like to avoid to have a parameter in the constructor. I also want to verify that the SerializableAs is exactly the same as the identifier.
Is there a way to do this?
Thanks
EDIT: Here is a link to the SerializeAs annotation I work with: https://github.com/Bukkit/Bukkit/blob/master/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java
EDIT: Found it, I am stupid, it works as expected. Thanks!
Upvotes: 1
Views: 2596
Reputation: 279970
Don't forget to annotate your annotation with
@Retention(RetentionPolicy.RUNTIME)
This will make it available (through reflection) at run time.
I also want to verify that the
SerializableAs
is exactly the same as the identifier.
You'll have to validate the value returned by value()
yourself at run time.
Note that nothing in your code is forcing an implementation of Skill
to have an annotation. Someone could make a sub type that doesn't have it. You should take that into account and maybe move your logic to somewhere else or change the logic to also do a null
check.
Upvotes: 3