Java Generic class extends parameterized type

Assume the following existing classes:

class A { public void foo() { ... }; ... } class A1 extends A { ... }; class A2 extends A { ... }; ... class A1000 extends A { ... }; 

now we need to create a variant of each Axx class that overrides the "foo" method. The main idea was as follows:

 class B<T extends A> extends T { @Override public void foo () { ... }; } 

But it is not possible to extend a class from one of their parameterized types.

The goal is to skip the following code:

 class B1 extends A1 { @Override public void foo() { ... }; }; class B2 extends A2 { @Override public void foo() { ... }; }; .... class B1000 extends A1000 { @Override public void foo() { ... }; }; 

and allow statements such as:

 ... B<A643> b643 = new B<A643>; b643.foo(); ... 

Any clues?

Thank you very much.

+6
source share
3 answers

Finally, resolved using the proxy class. The standard reflection.proxy is not applicable, but the proxy is from the CGLib librarian. In short, an interceptor with the same code as "B.foo" is used. See reflection.proxy is not valid when overriding . Thanks to Tagir Valeev for help.

0
source

A not common. I think you need something like:

 class B<T> extends A { @Override public void foo () { ... }; } 

This is a generic type B that extends A ... T extends A means that B accepts a type that extends A (not B extends A ).

+5
source

You can mix inheritance with delegation. I find this ugly, but it should work.

 class UniversalB extends A{ A a; UniversalB(A a) { this.a = a; } @Override public void foo() { ... }; // @Override any other method from A you want/need // and delegate it to the passed member if necessary } UniversalB b = new UniversalB(new A123()); b.foo(); b.anyMethodInA(); 
+1
source

Source: https://habr.com/ru/post/986963/


All Articles