Passing the argument to be used by the instance

I have a parser that has this construct for about a million 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 have a wetware error and cannot determine the tokenType class in the method. Another problem is that Java treats the token type as a literal. I.e:

 instanceof tokenType

looks just like

 instanceof CommaToken

regarding syntax.

Any ideas?

+5
source share
1 answer

You can do this 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 ... }  
}
+8
source

All Articles