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?
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 ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With