如何在java中启动泛型类型

时间:2012-12-06 13:42:33

标签: java generics

我的代码是:

class ReferenceRangeBuilder<T extends DvOrderedBuilder> {

private DvTextBuilder meaningBuilder;
private DvIntervalBuilder<T> rangeBuilder;
   public ReferenceRangeBuilder() throws ClassNotFoundException, InstantiationException, IllegalAccessException {

}

}

我想启动rangeBuilder,以便我可以为其设置值。 我想在构造函数中做到这一点。 对于DvIntervalBuilder rangeBuilder我做的就像:

 public DvIntervalBuilder() throws NoSuchFieldException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
        // You may need this split or not, use logging to check
        String parameterClassName = pt.getActualTypeArguments()[0].toString().split("\\s")[1];

        T lower = (T) Class.forName(parameterClassName).newInstance();
        T upper = (T) Class.forName(parameterClassName).newInstance();

    }

3 个答案:

答案 0 :(得分:1)

我通过编写这样的构造函数来解决问题,感谢所有有价值的时间和意见。

我的解决方案是:

public ReferenceRangeBuilder(Class<T> claz) {
    try {
        lowerReferenceRange = claz.newInstance();
        upperReferenceRange = claz.newInstance();
    } catch (InstantiationException ex) {
        Logger.getLogger(ReferenceRangeBuilder.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(ReferenceRangeBuilder.class.getName()).log(Level.SEVERE, null, ex);
    }
}

答案 1 :(得分:0)

您是否询问是否可以在构造函数中创建T实例?由于Java中实现了泛型的方式,因此在运行时无法获得此信息。阅读“类型擦除”以获取更多信息。 http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

答案 2 :(得分:0)

要使这种方法起作用,您的构建器必须是子类,否则类型在运行时是未知的。

public class Main {
    static class Builder<T> {
        private final Class clazz;

        protected Builder() {
            Type type = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            if (type instanceof Class)
                clazz = (Class) type;
            else
                throw new AssertionError("Builder needs to be sub-classed as " + type + " is unknown");
        }

        public Class<T> getClazz() {
            return clazz;
        }
    }

    public static void main(String... args) {
        // works fine as sub-class records that the type is BigDecimal.
        Builder<BigDecimal> bigDecimalBuilder = new Builder<BigDecimal>() {
        };
        System.out.println(bigDecimalBuilder.getClazz());
        // doesn't work.
        Builder<BigDecimal> bigDecimalBuilder2 = new Builder<BigDecimal>();
    }
}

打印

class java.math.BigDecimal

Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    at Main$Builder.<init>(Main.java:21)
    at Main.main(Main.java:37)