Get a list of all Java reserved Keywords

安稳与你 提交于 2020-01-13 09:45:10

问题


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


回答1:


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

import java.util.Arrays;

    public class MainDemo {
        static final String keywords[] = { "abstract", "assert", "boolean",
                "break", "byte", "case", "catch", "char", "class", "const",
                "continue", "default", "do", "double", "else", "extends", "false",
                "final", "finally", "float", "for", "goto", "if", "implements",
                "import", "instanceof", "int", "interface", "long", "native",
                "new", "null", "package", "private", "protected", "public",
                "return", "short", "static", "strictfp", "super", "switch",
                "synchronized", "this", "throw", "throws", "transient", "true",
                "try", "void", "volatile", "while" };

        public static boolean isJavaKeyword(String keyword) {
            return (Arrays.binarySearch(keywords, keyword) >= 0);
        }

        //Main method
        public static void main(String[] args) {
            System.out.println(isJavaKeyword("void"));

        }

    }

Output:

True


Alternatively, as users @typeracer,@holger suggested in the comments, you can use SourceVersion.isKeyword("void") which uses javax.lang.model.SourceVersion library and Hashset Data structure internally and keeps the list updated for you.




回答2:


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.

 public static String[] keys= {  "new",..... } 

then

 for (int i = 0; i < keys.length; i++) {  
            if (input.equals(keys[i])) {  
               // TO DO
            }  
        }  



回答3:


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




回答4:


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:

SourceVersion.isKeyword(str)

And if you really need the full list of the reserved keywords, you can obtain it from the source code of that class:

private final static Set<String> keywords;
static {
    Set<String> s = new HashSet<String>();
    String [] kws = {
        "abstract", "continue",     "for",          "new",          "switch",
        "assert",   "default",      "if",           "package",      "synchronized",
        "boolean",  "do",           "goto",         "private",      "this",
        "break",    "double",       "implements",   "protected",    "throw",
        "byte",     "else",         "import",       "public",       "throws",
        "case",     "enum",         "instanceof",   "return",       "transient",
        "catch",    "extends",      "int",          "short",        "try",
        "char",     "final",        "interface",    "static",       "void",
        "class",    "finally",      "long",         "strictfp",     "volatile",
        "const",    "float",        "native",       "super",        "while",
        // literals
        "null",     "true",         "false"
    };
    for(String kw : kws)
        s.add(kw);
    keywords = Collections.unmodifiableSet(s);
}

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.



来源:https://stackoverflow.com/questions/24265110/get-a-list-of-all-java-reserved-keywords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!