Java中的通用方法 – 如何将参数类类型作为返回类型返回

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

Generic Method in Java - How to return the param class type as return type

问题

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

  1. public <T> T getJsonPojo(String fileName, Class<T> classType) {
  2. try {
  3. return objectMapper.readValue(new File(classLoader.getResource(fileName).getFile()), classType);
  4. } catch (IOException e) {
  5. e.printStackTrace();
  6. }
  7. return null;
  8. }

现在我可以这样调用:

  1. A obj = getJsonPojo("filePath", A.class);
英文:

How to return the same classType (2nd param) as return type?

  1. public Object getJsonPojo(String fileName, Class classType) {
  2. try {
  3. return objectMapper.readValue(new File(classLoader.getResource(fileName).getFile()), classType);
  4. } catch (IOException e) {
  5. e.printStackTrace();
  6. }
  7. return null;
  8. }

Now I can call like below only

  1. A obj = (A) getJsonPojo(&quot;filePath&quot;, A.class);

I want to have something like below, for example (without casting):

  1. A obj = getJsonPojo(&quot;filePath&quot;, A.class);

答案1

得分: 1

使用方法级别的通用参数和显式转换。

  1. public <T> T getJsonPojo(String fileName, Class<T> classType) {
  2. try {
  3. File file = new File(classLoader.getResource(fileName).getFile());
  4. return (T) objectMapper.readValue(file, classType);
  5. } catch (IOException e) {
  6. e.printStackTrace();
  7. }
  8. }

或者,通用类型 <T> 可以存在于类级别。

无论哪种情况,都不要使用原始的 Class,而是指定通用类型 Class<T>

英文:

Use the generic parameter at the method level and the explicit casting.

  1. public &lt;T&gt; T getJsonPojo(String fileName, Class&lt;T&gt; classType) {
  2. try {
  3. File file = new File(classLoader.getResource(fileName).getFile());
  4. return (T) objectMapper.readValue(file, classType);
  5. } catch (IOException e) {
  6. e.printStackTrace();
  7. }
  8. }

Alternatively, the generic type &lt;T&gt; can be present at the class level.

In any case, don't use raw Class but specify a generic type Class&lt;T&gt;.

huangapple
  • 本文由 发表于 2020年8月3日 03:32:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63220241.html
匿名

发表评论

匿名网友

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

确定