Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compare generic type with Void

I have problem with comparing java generic type if it is type of Void or not. In other words I'm trying to ensure if my generic type T is Void or not. My sample implementation:

public abstract class Request<T>{

     private T member;

     protected void comparing(){
         if(T instanceof Void) // this make error "Expression expected"
             runAnotherMethod();

         //if I type
         if(member instanceof Void) //Incovertible types; cannot cast T to java.lang.Void
             runAnotherMethod();
     }

     protected void runAnotherMethod(){...}
}

public class ParticularRequest extends Request<Void>{
}

I've tried to compare id via instanceof, Class<T> and Class<Void>, T.class and Void.class. But the AndroidStudio show me error in every tried case :(

can you help me how to compare it? thanks.

like image 302
feromakovi Avatar asked Sep 04 '26 07:09

feromakovi


1 Answers

When using java generics you often need to ask for the class of the generic type in the constructor so that you can actually work with the class. I guess, that is a confusing sentence so just see the example below:

public abstract class Request<T> {

    private Class<T> clazz;

    // constructor that asks for the class of the generic type
    public Request(Class<T> clazz) {
        this.clazz = clazz;
    }

    // helper function involving the class of the generic type.
    // in this case we check if the generic type is of class java.lang.Void
    protected boolean isVoidRequest(){
        return clazz.equals(Void.class);
    }

    // functionality that depends on the generic type
    protected void comparing() {
        if (isVoidRequest()) {
            runAnotherMethod();
        }
    }

    // ...
}

When you subclass you must pass the class of the generic type to the super constructor.

public class LongRequest extends Request<Long> {
    public LongRequest() {
        super(Long.class);
    }
}

public class VoidRequest extends Request<Void> {
    public VoidRequest() {
        super(Void.class);
    }
}
like image 161
Rob Meeuwisse Avatar answered Sep 06 '26 21:09

Rob Meeuwisse