简体   繁体   中英

Java Generic - subtypes check?

How do I check generic subtypes passed as parameter?

For example:

public class A<T> { public T get();}
public class AString extends A<String> {}
public class ADate extends A<Date> {}

public void checkparam(List<? extends A<?>> params) {
///Want to check if params is of type List<AString> or List<ADate> ?
}

Is it possible? What part I am not understanding?

It is not possible because generic type information like that is erased and not available at runtime. At runtime, all that is known is that the parameter to checkparam is a List .

I don't believe you can do it directly on the list. You could do a check on the first element:

if (!params.isEmpty() && params.get(0) instanceof AString) {
   // it's List<AString>
}
...

Not pretty and won't work on empty lists, but should work otherwise.

This is made clear by trying to compile the following code:

import java.util.Date;
import java.util.List;

public class A<T> { 
    private T value;

    public T get() {
        return value;
    }

    public void checkparam(List<AString> list) {

    }

    public void checkparam(List<ADate> list) {

    }
}
class AString extends A<String> {}
class ADate extends A<Date> {}

which produces the following output from javac:

$ javac A.java 
A.java:11: name clash: checkparam(java.util.List<AString>) and checkparam(java.util.List<ADate>) have the same erasure
    public void checkparam(List<AString> list) {
                ^
A.java:15: name clash: checkparam(java.util.List<ADate>) and checkparam(java.util.List<AString>) have the same erasure
    public void checkparam(List<ADate> list) {
                ^
2 errors

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