简体   繁体   中英

How should I reflectively instantiate a parametrized type using guava TypeToken?

My class TypeRegisterer allows a client to register parameterized types (with the same parameter as TypeRegisterer) and then instantiate them by using their raw type name.

My current solution works but I have an unchecked cast warning and I'm not sure whether it's safe to ignore. Is there a better way to do this?

public class TypeRegisterer<T> {
    private Map<String, TypeToken<? extends Base<T>>> registeredTypes;

    public void registerType(TypeToken<? extends Base<T>> typeToken) {
        registeredTypes.put(typeToken.getRawType().getSimpleName(), typeToken);
    }

    public Base<T> initType(String className, T feature) throws Exception {
        // validation and exception handling removed for brevity
        TypeToken<? extends Base<T>> ruleType = registeredTypes.get(className);

        @SuppressWarnings("unchecked")
        Class<? extends Base<T>> rawType = (Class<? extends Base<T>>) ruleType .getRawType();

        return rawType.getConstructor().newInstance();
    }
}

This is OK - parameterized types are compiled with type erasure , so the parameter information isn't available at runtime.

At runtime, Class<Base<T>> == Class<Base<Integer>> == Class<Base<Double>> etc, so the class object referenced by your rawType variable is sufficient to instantiate the 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