我有一个参数化的接口RestHandler。

public interface RestHandler<T> {
   blah blah blah...
}

我需要使用Class.forName从配置创建一个类。现在,我提出了三个版本,所有版本均可成功编译。

版本1:
@SuppressWarnings("unchecked")
public static <T> RestHandler<T> create(final String handlerImplFqcn) throws ClassNotFoundException,
                                                                    IllegalAccessException,
                                                                    InstantiationException {
    Class<?> handlerClass = Class.forName(handlerImplFqcn);
    return (RestHandler<T>) handlerClass.newInstance();
}

版本2:
public static RestHandler<?> create(final String handlerImplFqcn) throws ClassNotFoundException,
                                                                    IllegalAccessException,
                                                                    InstantiationException {
    @SuppressWarnings("rawtypes")
    Class handlerClass = Class.forName(handlerImplFqcn);
    return (RestHandler<?>) handlerClass.newInstance();
}

版本3:
public static RestHandler<?> create(final String handlerImplFqcn) throws ClassNotFoundException,
                                                                    IllegalAccessException,
                                                                    InstantiationException {
    Class<?> handlerClass = Class.forName(handlerImplFqcn);
    return (RestHandler<?>) handlerClass.newInstance();
}

我的问题是,为什么它们都起作用,哪种是最佳实践?

最佳答案

版本1,改写为:

public static <T extends RestHandler<?>> RestHandler<T> create(final String handlerImplFqcn) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ClassCastException {
    Class<T> handlerClass = (Class<T>) Class.forName(handlerImplFqcn);
    return (RestHandler<T>) handlerClass.newInstance();
}

关于java - Java泛型用于参数化类:无限通配符与原始类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28319662/

10-10 15:16