开发者

Remove Annotations in Subclass?

i have a child Class, that needs an Annotation, that is declared in the Parent class removed. What is the best way to do this?

public class Parent

@MyAnnoation
String foobar;

}


public class Child extends Parent {
//here I only want to remove the @MyAnnotation from String foobar;

}

What I want to avoid is, "overriding" the member

 public class Child extends Parent {

 String foobar;

 }

as this has several disadvantages (as it "covers" the underlaying parent member = this.开发者_开发技巧foobar can be different to super.foobar)...

1.) Is there an easy way of removing an annotation from a Parent Class in the Subclass (here Child)?

2.) What is the official way to remove annotations in a Subclass?

Thanks very much! Markus


If you want to do something like this than you probably should have another look at your design.

I think that if there is a way to remove a runtime annotation than that would not be recommended, because you would be remove a part of a class definition. Like removing a member access modifier for instance.

That can have unexpected results on your logic since other code might rely on these definitions to make runtime decisions.

If you need to modify a class definition during runtime than this class should probably not be defined in such a way in the first place.


To my knowledge you can't remove annotations. But this may help:

  1. Not all annotations are available at runtime. So, in that case obviously there's no reason to remove them. Only annotations with a @Retention(RUNTIME) are available at runtime. (e.g. @Nullable annotations are not available at runtime, but @XmlElement is.).

  2. Only for class-level annotations, there's another thing to take in account. Not all annotations are inherited automatically to child classes. This is only the case for annotations which have an @Inherited annotation of their own.

  3. Some annotations can be contradicted by redeclaring a different annotation. (e.g. a parent class with @XmlAccessorType(FIELD) can have a child class with @XmlAccessorType(PUBLIC).)

So, removing is impossible, but redefining/replacing is. In practice that means that the effect of some annotations can be "removed" by setting them to their default value @MyAnnotation(NONE) or @MyAnnotation(DEFAULT) or @NotMyAnnotation. So, that means it really depends what kind of annotations you are dealing with.

One more thing: Even though you can redefine annotations on child classes, still it doesn't always give the desired effect. (e.g. In the case of @XmlElement sometimes the annotation on the parent method still has priority during execution). It's good to know that some frameworks (e.g. persistence) support alternative xml binding files as an alternative to java class annotations).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜