我将创建一个通用类,首先我想说一下我的要求。我有不同的类(class),例如A、B 等。我将基于 json 对象创建一个类的实例。该 json 对象将从文件中读取。该文件可能包含等效的 json 对象。基于它,我将使用 GSON 创建该类的实例。现在我面临一个错误,即不兼容的类型:T#1 无法转换为 T#2
这是我的代码示例
public class JsonLoader<T> {
private final Gson gson = new Gson();
private final T content;
public <T> JsonLoader(Class<T> clazz, String filePath) throws IllegalFileException {
if (filePath.isEmpty() || filePath == null) {
throw new IllegalFileException("IllegalFileException: source file must required.");
}
try (Reader reader = new FileReader(filePath)) {
T content= gson.fromJson(reader, clazz);
this.content = content;
} catch (IOException e) {
throw new IllegalFileException(e.getMessage(),e);
}
}
public <T> T getObject() {
return this.content;
}
}
请帮助我。
最佳答案
当您声明类型参数 T
时在类上,整个类主体都可以访问该类型参数,因此您不需要重新声明它。当你说public <T> JsonLoader
时和public <T> T getObject
您实际上是在声明具有相同名称的新类型参数,这会隐藏类上的类型参数。
这类似于声明隐藏字段的变量的方式:
class Example {
int foo;
// parameter foo shadows the field foo
Example(int foo) {}
}
如果删除构造函数和方法上的类型参数声明,它应该可以正常工作。
关于java - 不兼容的类型 : T#1 cannot be converted to T#2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45319280/