I have a global variable page
private T page
In addition, I have a setter method;
public <T> void setGenericVar(T page) {
this.page = page
}
My calls in the main program are like this;
setGenericVar("one");
setGenericVar(1);
The error I'm getting is in the setter method which is:
Required type: T
Provided: T
"Change parameter 'page' type to 'T'"
I'm requiring in the function a T parameter but I'm also proving it, so I do not get this error!
EDIT: The problem appears with this code:
public class GenericVariables<T> {
private T page;
public void main (String args[]) {
setGenericVar(2);
}
public <T> void setGenericVar(T page) {
this.page = page
}
}
The problem happens because of what lealceldeiro mentions in a comment: you have specified a type parameter on the class as well as on the method. These are both named
T, but they are separate type parameters, so they are really different.If you give them different names, it will be easier to see what's going on:
Solution: Remove the type parameter from the method; just let it use the type parameter of the class.
Note: Your
mainmethod is notstatic, therefore Java will not see this as the entry point for your program; you cannot run your program starting from thismainmethod. You need to make itstatic. If you do that, you cannot call thesetGenericVarmethod directly. You'll need to create an instance of the class and call the method on that: