【问题标题】:Generic Method in Java - How to return the param class type as return type [duplicate]Java中的通用方法-如何将参数类类型作为返回类型返回[重复]
【发布时间】:2020-11-22 23:27:17
【问题描述】:

如何返回与返回类型相同的classType(第二个参数)?

public Object getJsonPojo(String fileName, Class classType) {
    try {
        return objectMapper.readValue(new File(classLoader.getResource(fileName).getFile()), classType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

现在我只能像下面这样调用

A obj = (A) getJsonPojo("filePath", A.class); 

我想要像下面这样的东西,例如(不强制转换):

A obj = getJsonPojo("filePath", A.class);

【问题讨论】:

  • 这能回答你的问题吗? How do I make the method return type generic?
  • new File(classLoader.getResource(fileName).getFile()) ← 不要那样做。 URL.getFile() 方法返回有效的文件名。如果将应用程序打包为单个 .jar 文件,则资源根本就不是文件。要么使用 getResourceAsStream,要么,如果 fileName 确实是项目之外的文件,则完全避免使用 getResource 方法,而只使用 FileInputStream。
  • filrName 是文件 insdie 资源文件夹的路径。例如:如果文件存在于资源/a/b/sample.json 中,我将指定为“a/b/sample.json”
  • 感谢@PrathapReddy,通过您提供的链接,我学到了更多东西。

标签: java generics


【解决方案1】:

在方法级别使用泛型参数和显式转换。

public <T> T getJsonPojo(String fileName, Class<T> classType) {
    try {
        File file = new File(classLoader.getResource(fileName).getFile());
        return (T) objectMapper.readValue(file, classType);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

或者,泛型类型&lt;T&gt; 可以出现在类级别。

无论如何,不​​要使用原始的Class,而是指定一个泛型类型Class&lt;T&gt;

【讨论】:

  • 我的错误,已编辑。
  • 谢谢@Nikolas,完美!
  • 不客气 :) 考虑将答案标记为已接受,让其他人知道这个问题有解决方案。如果您愿意,也欢迎您询问详细信息和/或编辑您的问题。
  • @AbdulBasith 启用所有编译器警告将在未来通知您此类错误。
  • @VGR 我不明白你的意思。尼古拉斯的回答对我有用。你指的是什么?
猜你喜欢
  • 1970-01-01
  • 2017-12-14
  • 2015-05-16
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2018-10-19
相关资源
最近更新 更多