Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 404
Tony Ennis Avatar asked Mar 10 '12 04:03

Tony Ennis


1 Answers

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 ... }  
}
like image 196
Kaleb Brasee Avatar answered Oct 17 '22 16:10

Kaleb Brasee