Search code examples
javainstanceof

passing an argument to be used by instanceof


I have a parser that has this construct about a zillion times:

if (tokens.first() instanceof CommaToken) {
    tokens.consume();

I would like to know how to do this:

if (match(CommaToken)) { ... blah ... }

private boolean match(??? tokenType) {
    if (tokens.first() instanceof tokenType) { ... blah ... }  
}

I'm having a wetware failure and can't figure out the class of tokenType in the method. Another problem is that Java is treating 'tokenType' as a literal. That is:

 instanceof tokenType

looks just like

 instanceof CommaToken

with respect to syntax.

Any ideas?


Solution

  • You can do this by using Class objects via class (to get a Class object from a class reference) and getClass() (to get a Class object from an instance):

    if (match(CommaToken.class)) { ... blah ... }
    
    private boolean match(Class<?> klass) {
        if (tokens.first().getClass().equals(klass)) { ... blah ... }  
    }