获取所有Java保留关键字的列表 [英] Get a list of all Java reserved Keywords

查看:303
本文介绍了获取所有Java保留关键字的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来将Java中保存的所有关键字检索到某种数据结构中。例如:for,while,if,else,int,double等。

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."

我需要对字符串进行名称验证,具体来说,我需要确保它不等于任何java关键字。

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.

是否有一种特定的方法可以将所有关键字检索到一个数据结构中?或者我是否需要构建一个包含所有这些关键字的正则表达式字符串:for | while | if | ...并尝试匹配我的字符串吗?

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?

谢谢

推荐答案

来自 axis.apache.org

基本上,预先排序关键字并将其存储在数组中并使用 Arrays.binarySearch 关于good'ol的关键字 O(logn)复杂性

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"));

        }

    }

输出:

True

这篇关于获取所有Java保留关键字的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆