简体   繁体   English

我们可以通过传递类类型作为参数来使用 Java 泛型创建不同的类实例吗

[英]Can we create different class instance using Java generics by passing class type as argument

I am trying to create object from a xml file.我正在尝试从 xml 文件创建对象。 Currently I am providing the Class type to be parsed in the method signature.目前我正在提供要在方法签名中解析的 Class 类型。 For instance TestRequest as you see in the below code.例如,您在下面的代码中看到的 TestRequest。 Due to this I cannot use the same method to create another object type.因此,我无法使用相同的方法来创建另一种对象类型。 Is it possible to write a method, probably using generics, to return different class instance by passing class type as parameter.是否可以编写一个方法,可能使用泛型,通过将类类型作为参数传递来返回不同的类实例。

Current Code:当前代码:

  private static JAXBElement<TestRequest> createRequestObject(String xmlFile) {

    JAXBElement<VerifyRequest> result;
    try {
      JAXBContext ctx = JAXBContext.newInstance(TestRequest.class);
      Unmarshaller unmarshaller = ctx.createUnmarshaller();
      String xmlString = loadFile(xmlFile);
      result = unmarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(xmlString.getBytes())), VerifyRequest.class);
    } catch (JAXBException | IOException e) {
      throw new RuntimeException(e);
    }
    return result;
  }

Expecting something like期待类似的东西

private static <T> JAXBElement<T> createRequestObject(String xmlFile, Class objectType) {
private static <T> JAXBElement<T> 
createRequestObject (String xmlFile, Class<T> type)

That should be enough.那应该就够了。

If you call createRequestObject(file, TestRequest.class) , T is resolved to be TestRequest and thus the return type would be JAXBElement<TestRequest> .如果您调用createRequestObject(file, TestRequest.class) ,则T被解析为TestRequest ,因此返回类型将为JAXBElement<TestRequest> Similar for other types.其他类型类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM