Plan B

Sunday Jan 21, 2007

Programmatically looking up Java reserved words

(Warning: the solution discussed is specific to Sun's javac compiler and is not "vendor" agnostic)

Let's say during code generation, you want to make sure that you don't use java reserved words as identifiers. Trivially, you could go through the hassle of creating an Enum for yourself and manually populating it with known reserved words for that version of Java. But, why reinvent the wheel when the compiler already has that information (updated per release)? All you need to do is create an EnumSet from the Enum com.sun.tools.javac.parser.Token and look it up to know if a certain String is a java reserved word.

The only problem with this approach is that it relies upon an implementation specific class/package(com.sun.* can change without notice and do not constitute an API). But if laziness takes over, its still an option worth considering for one-off usage. Of course, I'd like to know better (implementation independent) alternatives.

Thanks to Sundar for providing pointers in the javac source.


Comments:

hello sir, I plan to just build a small editor to just check the syntax of the java code, and underline the errors with the line number as it happens with any ides. i also intend to have another utility where in the code complies to the coding conventions set by the user. So i wanted to know how to make use of javac api for the same or should i use different api. As there no much documentation on this i request you to throw some light on this.. Thank you Regards Ranganath.S

Posted by Ranganath.s on January 23, 2007 at 04:40 PM IST #

Ranganath, You're probably looking for http://lexer.netbeans.org You should mail nbdev [at] netbeans [dot] org for questions on imposing code-convention rules and for using the javac API.

Posted by Bharath R on January 23, 2007 at 06:41 PM IST #

thanks alot , its a real good resource to move ahead..

Posted by Ranganath.S on January 24, 2007 at 02:45 PM IST #

Post a Comment:
Comments are closed for this entry.

Calendar

Feeds

Search

Links

Navigation

Referers