Gets a list of all Java reserved keywords
•
Java
I'm looking for a way to retrieve all the keywords saved in Java into a data structure For example: "for, while, if, else, int, double, etc."
I need to verify the name of the string. Specifically, I need to ensure that it is not equal to any Java keyword
Is there a specific way to retrieve all keywords into a data structure? Or do I need to build a regular expression string containing all these keywords: "for | while | if |..." and try to match my string?
thank you
Solution
From axis apache. Org
Basically, pre sort the keywords and store them in an array, and use arrays. On the keywords Binary search to obtain good'ol o (log n) 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:
real
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码