14

Get a list of all reserved Java keywords

 2 years ago
source link: https://www.codesd.com/item/get-a-list-of-all-reserved-java-keywords.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Get a list of all reserved Java keywords

advertisements

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


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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK