能否通过Java系统库获取Java关键字存入HashTable?需手动编写吗?
Great question—you absolutely don’t have to manually hardcode all Java keywords into a Hashtable or other container. The Java standard library provides a reliable, version-aware way to fetch them automatically, which avoids typos, missing keywords (like newer ones added in recent Java versions), and the hassle of maintaining a list yourself.
Recommended Approach (Java 9+)
Use the javax.lang.model.SourceVersion class, which is part of the standard API and designed for this exact purpose. It returns all keywords applicable to the latest supported Java version, so it’ll automatically include new keywords like sealed, permits, or value as they’re added.
Here’s a quick example to populate a Hashtable (or any collection) with keywords:
import javax.lang.model.SourceVersion; import java.util.Hashtable; public class KeywordLoader { public static void main(String[] args) { // Fetch all keywords as a Set var javaKeywords = SourceVersion.latest().keywords(); // Populate a Hashtable (if you specifically need this legacy class) Hashtable<String, Boolean> keywordTable = new Hashtable<>(); for (String keyword : javaKeywords) { keywordTable.put(keyword, Boolean.TRUE); } // Test it out System.out.println("Is 'for' a keyword? " + keywordTable.containsKey("for")); // true System.out.println("Is 'while' a keyword? " + keywordTable.containsKey("while")); // true System.out.println("Is 'myVar' a keyword? " + keywordTable.containsKey("myVar")); // false } }
For Java 8 or Earlier (Deprecated Option)
If you’re stuck on Java 8, the java.lang.Compiler class has a deprecated keywords() method that returns an array of keywords. Note that this method is marked deprecated and may be removed in future versions, so upgrading to Java 9+ is strongly preferred.
Example for Java 8:
import java.util.Hashtable; public class LegacyKeywordLoader { public static void main(String[] args) { // Get keywords (deprecated method) String[] keywordArray = java.lang.Compiler.keywords(); Hashtable<String, Boolean> keywordTable = new Hashtable<>(); for (String keyword : keywordArray) { keywordTable.put(keyword, Boolean.TRUE); } } }
What to Avoid
Steer clear of internal APIs like com.sun.tools.javac.parser.Keywords—these are part of the JDK’s internal implementation, not the standard API. They can change or disappear between JDK versions (or across different JDK distributions like OpenJDK vs. Oracle JDK), making your code unstable.
Final Note
Using the standard library’s built-in methods is always better than manual listing: it’s less error-prone, automatically adapts to Java version changes, and saves you the trouble of updating your keyword list every time a new Java release comes out.
内容的提问来源于stack exchange,提问作者user3741086

