不兼容的类型:T#1 不能转换为 T#2

Sub*_*dal 0 java generics gson

我将创建一个通用类,首先我想说一下我的要求。我有不同的类,例如 A、B 等。我将基于 json 对象创建一个类的实例。这个 json 对象将从文件中读取。该文件可能包含等效的 json 对象。基于它,我将使用 GSON 创建该类的实例。现在我面临一个错误,即incompatible types: T#1 cannot be converted to 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮我。

Rad*_*def 5

当您在类T上声明类型参数时,整个类主体都可以访问该类型参数,因此您无需重新声明它。当您说public <T> JsonLoader并且public <T> T getObject您实际上是在声明具有相同名称的新类型参数时,这些参数会影响类上的类型参数。

这类似于如何声明一个隐藏字段的变量:

class Example {
    int foo;
    // parameter foo shadows the field foo
    Example(int foo) {}
}
Run Code Online (Sandbox Code Playgroud)

如果您删除构造函数和方法上的类型参数声明,它应该可以正常工作。