Search code examples
javagenericsglobal-variablessettergeneric-method

Setting generic variable value in Java


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

Solution

  • 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.

    public class GenericVariables<T> { // Type parameter <T> on class here
        private T page;
    
        public void main (String args[]) {
            setGenericVar(2);
        }
    
        // Type parameter <T> on method here
        public <T> void setGenericVar(T page) {
            this.page = page;
        } 
    }
    

    If you give them different names, it will be easier to see what's going on:

    public class GenericVariables<T> {
        private T page;
    
        public void main (String args[]) {
            setGenericVar(2);
        }
    
        public <U> void setGenericVar(U page) {
            // ERROR: this.page is of type T, but the parameter page is of type U
            this.page = page;
        } 
    }
    

    Solution: Remove the type parameter from the method; just let it use the type parameter of the class.

    public class GenericVariables<T> {
        private T page;
    
        public void main (String args[]) {
            setGenericVar(2);
        }
    
        public void setGenericVar(T page) {
            this.page = page;
        } 
    }
    

    Note: Your main method is not static, therefore Java will not see this as the entry point for your program; you cannot run your program starting from this main method. You need to make it static. If you do that, you cannot call the setGenericVar method directly. You'll need to create an instance of the class and call the method on that:

    public class GenericVariables<T> {
        private T page;
    
        public static void main (String args[]) {
            GenericVariables<Integer> object = new GenericVariables<>();
            object.setGenericVar(2);
        }
    
        public void setGenericVar(T page) {
            this.page = page;
        } 
    }