Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I annotate a member inherited from a superclass?

If I have a class such as:

class Person {
  private String name;
  ...constructor, getters, setters, equals, hashcode, tostring...
}

Can I subclass and apply annotations to the name field in the subclass, for example to apply persistence annotations, without re-implementing the rest of the class?

@Entity
class Employee extends Person {
    @Column(...)
    private String name;
}
like image 600
brabster Avatar asked Jun 26 '13 11:06

brabster


People also ask

Can annotation be inherited?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it.

Are Spring annotations inherited?

Annotations on methods are not inherited by default, so we need to handle this explicitly.

What is the use of inherited annotation?

Annotation Type Inherited If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type.

What will be inherited in subclass from superclass in inheritance?

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.


1 Answers

That wont work since the fields in super class will not be affected, but you can try this

@Entity
class Employee extends Person {
  @Column(name="xxx")
  @Override
  public void setName(String name) {
     super.setName(name);
  }
  ...
like image 121
Evgeniy Dorofeev Avatar answered Oct 16 '22 13:10

Evgeniy Dorofeev