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

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

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

问题

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

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

现在我可以这样调用:

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

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

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;
}

Now I can call like below only

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

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

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

答案1

得分: 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();
    }
}

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

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

英文:

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

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

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:

确定