Subhabrata Mondal Subhabrata Mondal - 3 years ago 166
Java Question

incompatible types: T#1 cannot be converted to T#2

I am going to create one generic class, first i want to say my requirement. I have different classes e.g. A,B etc. I am going to create an instance of class based on the json object. This json object will be read from file. The file may contain equivalent json object.based on it i will create an instance of that class using GSON. Now i face one error i.e.

incompatible types: T#1 cannot be converted to T#2


This is my code sample

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


Please help me.

Answer Source

When you declare the type parameter T on the class, the entire class body has access to that type parameter, so you don't need to redeclare it. When you say public <T> JsonLoader and public <T> T getObject you are actually declaring new type parameters with the same name which shadow the type parameter on the class.

This is similar to how you can declare a variable which shadows a field:

class Example {
    int foo;
    // parameter foo shadows the field foo
    Example(int foo) {}
}

If you remove the type parameter declarations on the constructor and method it should just work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download