gpt4 book ai didi

Java T 初始化

转载 作者:行者123 更新时间:2023-11-29 06:02:50 24 4
gpt4 key购买 nike

如何创建类T?

我需要从对象 T 的某些 Windows Communication Foundation (WCF) XML 进行绑定(bind)。

我可以毫无错误地做到这一点:

ArrayList<T> list = new ArrayList<T>();

这是我的功能:

public static <T> ArrayList<T> GetListFromXml(String url,String element)

如何获取:T obj = ?

最佳答案

这是不可能的,因为 type erasure编译器。如果您在调用方有一个带有默认构造函数的具体类型,则以下方法可能有效:

public static <T> ArrayList<T> GetListFromXml(String url,String element, Class<? extends T> type) {
T obj = type.newInstance();
...
}

如果需要向构造函数传递参数,则必须通过getConstructor(parameter type 1, ...) 从类中获取(您需要处理此处未显示的异常) :

MyParamType1 param1 = ...;
MyParamType2 param2 = ...;
Constructor<T> cons = type.getConstructor(MyParamType1.class, MyParamType2.class);
T obj = const.newInstance(param1, param2);

关于Java T 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9518515/

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