0

我的代码是:

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();

    }
4

3 回答 3

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);
    }
}
于 2012-12-12T10:17:33.817 回答
0

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

于 2012-12-06T13:54:00.730 回答
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)      
于 2012-12-06T13:54:43.593 回答