gpt4 book ai didi

java - 从枚举到泛型的类型的映射

转载 作者:行者123 更新时间:2023-12-01 04:42:18 24 4
gpt4 key购买 nike

我正在编写一个类,它将数据(每个接口(interface)定义)写入不同的 xml 输出格式(不同的 JAXB 类)。所有支持的类型都存储在 Enum (SupportedTypes) 中。 Enum 存储相应的 JAXB-Class。枚举看起来像这样:

public enum Types {
/**
* Invoice from hospitals.
*/
Type1(...generatedClasses.invoice.hospital400.request.RequestType.class),
/**
* Invoice from hospital but with MediData's quality extensions. The
* response has no extensions.
*/
Type2(...generatedClasses.invoice.hospital400_QO.request.RequestType.class);

/**
* Class for request. represents the root element in corresponding xml.
*/
private Class<?> rType;

/**
*
* @param requestType
* class of corresponding request type
*/
private InvoiceTypes(final Class<?> requestType) {
this.requestType = requestType;
}

/**
* @return the requestType
*/
public final Class<?> getRequestType() {
return requestType;
}

}

我的问题是如何使用这种类型来实例化类型化泛型,例如 JAXBElement。 typeEnum 作为参数给出,我想创建 JAXBElement 但这显然不起作用。现在我被困住了。如何构造这样的构造函数或方法。

提前致谢

编辑以澄清:

假设您创建了一个支持不同类型的类(“ClassForTypes”)——无论它对它们做什么(TheirClass、SpecialClass、MyClass)。 API 不会发布这些类(它们非常具体),而是会发布一个“TypeEnum”(TypeOne、TypeTwo、TypeThree)来存储类的类型(TheirClass、SpecialClass、MyClass)。在 ClassForTypes 构造时,它将使用给定的 TypeEnum 来创建一个 List<type saved in enum> 。 。如何构造这样的 ClassForTypes 或其构造函数?

一些示例代码(不起作用):上面的枚举我想用这种方式:

public class Blub{

public Blub(Types type){
List<type.getRequestType> typedList = new ArrayList...
}

}

这不起作用。但是列表的类型在编译时是已知的(因为它存储在枚举中?)。有什么方法可以静态存储类型并使用它来获取类型化泛型吗?我不希望 api 用户知道有关单个请求类型的信息,用户应该只知道通过枚举传递的“支持的类型”。

最佳答案

您的问题不太清楚您到底想做什么。您是否正在尝试向枚举添加功能?像这样的吗?

public enum Types {
Type1(String.class) {
@Override
public Object make () {
return new String();
}
},
Type2(Integer.class) {
@Override
public Object make () {
return new Integer(0);
}
};

private Class<?> rType;

Types(final Class<?> requestType) {
this.rType = requestType;
}

public final Class<?> getRequestType() {
return rType;
}

// All types must have a make method.
public abstract Object make();
}

关于java - 从枚举到泛型的类型的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334855/

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