简体   繁体   中英

How to get the generic type of a generic class in JAVA

I have a class A

class A<V>{}

and class B extends A

class B extends A<V>{}

and class C have generic B, and I want to know the V from B

It is possible to do like this

class C<P extends B<V>,V>{
   P mP;
   V mV;
}

But since generic type of P(ie class B) knows it must have a V(ie class A), I do not have to specify V to know what V is when I create an object of C. I tried code like this but this is not valid

class C<P<V> extends B>{
   P mP;
   V mV;
}

I assume that

class B extends A<V>{}

is a typo as here, V had to be an actual type , eg a class , enum or interface with the name V that must be in scope, which must not be confused with A 's type parameter V , and since B would not be generic, P extends B<V> should not compile.

So I assume

class B<V> extends A<V>{}

In that setup,

class C<P extends B<V>,V>{
   P mP;
   V mV;
}

would be a valid declaration, introducing a new type parameter V and defining the relationship to B . In this situation, you can't omit V . If you were not using V within C , you could use class C<P extends B<?>> to denote that you don't care about the actual type parameter of B .

But since you are using V , it must be declared. This might be annoying to the users of C that wish to have V to be implied by the actual type they use for P , but there is no way around it in Java.

The closest you can get, would be to separate the class into a front-end class with a single type parameter and a specialized implementation class which can be instantiated without specifying the type arguments when using the “diamond operator”, ie

abstract class FrontEnd<T> {
    // define the API
}
class C<P extends B<V>, V> extends FrontEnd<P> {
   P mP;
   V mV;
}

…

FrontEnd<ActualSubtypeOfB> myObj = new C<>();

but unfortunately that would imply that the API of FrontEnd can not refer to V , so this is rarely sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM