Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
934 views
in Technique[技术] by (71.8m points)

regex - Get a list of all Java reserved Keywords

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...