简体   繁体   中英

Unable to obtain a class object of a generic type without using raw types

Consider the following:

public interface Converter<I, O> {
    public Class<I> getInputType();
    public Class<O> getOutputType();
}

If I implement the interface and fill the type parameters with non-generic types, everything is still fine:

public class ConverterImpl implements Converter<UUID, String> {
    public Class<UUID> getInputType() {
        return UUID.class;
    }
    public Class<String> getOutputType() {
        return String.class;
    }
}

However, if I implement the interface and fill the type parameters with generic types, here is the problem:

public class ConverterImpl<T> implements Converter<Collection<T>, String> {
    public Class<Collection<T>> getInputType() {
        return Collection.class; //Compile time error
    }
    public Class<String> getOutputType() {
        return String.class;
    }
}

because Collection.class returns Class<Collection> instead of Class<Collection<Something>> . However, raw types are designed only for backwards compatibility and is not recommended to use. Is using raw types the only solution for this situation?

You need to cast Collection.class to a Class<Collection<T>> . Try with this:

public Class<Collection<T>> getInputType() {
    return (Class<Collection<T>>) (Class) Collection.class;
}

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