I'm looking for a way to retrieve all the saved keywords in Java into some kind of data structure. For example: "for, while, if, else, int, double, etc."
I need to do a name validation on a string, to be specific, I need to make sure it does not equal to any java keywords.
Is there a specific way of retrieving all the keywords into one data structure? or do I need to just build a regex string with all these keywords in it : "for|while|if|..." and try and match my string against it?
Thanks
There is no direct API method. As an alternative, you take them in an array and check the entered keyword matches in the array if keywords.
then
I'm surprised that no one suggested javax.lang.model.SourceVersion yet, because it's actually been around since Java 1.6.
If you need to check whether some string is a reserved keyword, you can just call:
And if you really need the full list of the reserved keywords, you can obtain it from the source code of that class:
Caution: the above source code is from Java 1.8, so don't just copy & paste from this post if you're using a different version of Java. In fact, it's probably not a good idea to copy it at all — they made the field private for good reason — you probably don't want to have to keep it up-to-date for every new Java release. But if you absolutely must have it, then copy it from the source code in your own JDK distro, keeping in mind that you might have to manually keep updating it later.
From axis.apache.org
Basically, Pre-Sort the keywords and store it in an array and using Arrays.binarySearch on your keyword for the good'ol O(logn) complexity
Output:
True
Alternatively, as users @typeracer,@holger suggested in the comments, you can use
SourceVersion.isKeyword("void")
which usesjavax.lang.model.SourceVersion
library andHashset
Data structure internally and keeps the list updated for you.OK So since there is no automatic way of doing it, I will create a text file consisting of all the keywords : List of Java Keywords
And then at runtime go over the file, inserting each keyword into an array, or arraylist (or regex string) and check use that data structure when I check for name validity.
Thanks to everyone