gpt4 book ai didi

java - 如何在java中开始使用泛型类型

转载 作者:行者123 更新时间:2023-12-01 15:00:20 26 4
gpt4 key购买 nike

我的代码是:

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

}

最佳答案

我自己通过编写这样的构造函数解决了这个问题,感谢大家宝贵的时间和意见。

我的解决方案是:

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

关于java - 如何在java中开始使用泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13744864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com