获取所有Java保留关键字的列表

前端之家收集整理的这篇文章主要介绍了获取所有Java保留关键字的列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种方法来将 Java中保存的所有关键字检索到某种数据结构中.例如:“for,while,if,else,int,double等”

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

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

谢谢

解决方法

axis.apache.org

基本上,对关键字进行预排序并将其存储在一个数组中,并在关键字上使用Arrays.binarySearch以获得good’ol O(logn)复杂度

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

        }

    }

输出

真正

原文链接:https://www.f2er.com/java/127822.html

猜你在找的Java相关文章