Abhinab Kanrar
Abhinab Kanrar

Reputation: 1552

Inheritance with annotation in Java8

I know annotation can neither be inherited nor subclass/s contain parent level annotation. But, I have a simple scenario. Suppose, I have N number of classes like A,B,C,D......N.
A is the super class and B,C,D....N are the children i.e. subclass of A.So, if I need inheritence for these these classes I need to do it in following way:

class B extends A {
     //code
}

class C extends A {
     //code
}
......
class N extends A {
     //code
}

So I need to manually extends class A for N number of times.
Now, my question is couldn't I create a @ParentIsClassA like annotation, by which child level classes would automatically extend class A?
Sample code which I want to implement is below:

@ParentIsClassA
class B {
    //code
}

@ParentIsClassA
class N {
    //code
}

Upvotes: 1

Views: 716

Answers (1)

Annotations typically can't modify a class's compilation in Java. (Lombok uses special and fragile compiler hooks; Groovy ASTs can do what you're talking about.)

That said, why? You still have to insert that annotation just like the extends clause, and then you have issues like IDEs not understanding the relationships. Just use normal inheritance and don't confuse your tools and other programmers.

You might also be interested in the @Inherited meta-annotation.

Upvotes: 3

Related Questions