我们能否通过在Java泛型中传递类类型作为参数来创建不同的类实例

huangapple go评论85阅读模式
英文:

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

问题

以下是您想要的翻译内容:

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

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

I am trying to create object from a xml file. Currently I am providing the Class type to be parsed in the method signature. For instance TestRequest as you see in the below code. 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&lt;TestRequest&gt; createRequestObject(String xmlFile) {

    JAXBElement&lt;VerifyRequest&gt; 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 &lt;T&gt; JAXBElement&lt;T&gt; createRequestObject(String xmlFile, Class objectType) {

答案1

得分: 3

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>. Similar for other types.

英文:
private static &lt;T&gt; JAXBElement&lt;T&gt; 
createRequestObject (String xmlFile, Class&lt;T&gt; 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&lt;TestRequest&gt;. Similar for other types.

huangapple
  • 本文由 发表于 2020年9月30日 23:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64140573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定