01: package spoon.reflect.visitor;
02:
03: import java.util.Arrays;
04: import java.util.HashSet;
05: import java.util.Set;
06: import java.util.StringTokenizer;
07:
08: /**
09: * This enum defines the Java keywords and some helper method to determine if
10: * some strings are Java identifiers.
11: */
12: public enum JavaIdentifiers {
13:
14: IMPORT, PACKAGE, INTERFACE, CLASS, ENUM, SUPER, THIS, ASSERT, EXTENDS, BREAK, CASE, CATCH, CONTINUE, DO, FOR, IF, NEW, RETURN, SWITCH, THROW, TRY, WHILE,
15:
16: PUBLIC, PROTECTED, PRIVATE, ABSTRACT, STATIC, FINAL, TRANSIENT, VOLATILE, SYNCHRONIZED, NATIVE, STRICTFP;
17:
18: /**
19: * Contains the Java keywords.
20: */
21: public static Set<String> KEYWORDS;
22:
23: static {
24: KEYWORDS = new HashSet<String>();
25: for (JavaIdentifiers kw : Arrays.asList(JavaIdentifiers
26: .values())) {
27: KEYWORDS.add(kw.name().toLowerCase());
28: }
29: }
30:
31: static boolean isJavaIdentifier(String s) {
32: if (s.length() == 0
33: || !Character.isJavaIdentifierStart(s.charAt(0))) {
34: return false;
35: }
36: for (int i = 1; i < s.length(); i++) {
37: if (!Character.isJavaIdentifierPart(s.charAt(i))) {
38: return false;
39: }
40: }
41: return true;
42: }
43:
44: /**
45: * Ckecks if a string is a valid Java identifier and not a Java keyword.
46: *
47: * @param string
48: * the string to be tested
49: */
50: public static boolean isLegalJavaIdentifier(String string) {
51: if (string == null)
52: return false;
53: return !KEYWORDS.contains(string) && isJavaIdentifier(string);
54: }
55:
56: /**
57: * Ckecks if a string is a valid Java package identifier.
58: *
59: * @param string
60: * the string to be tested
61: */
62: public static boolean isLegalJavaPackageIdentifier(String string) {
63: if (string == null)
64: return false;
65: StringTokenizer st = new StringTokenizer(string, ".");
66: while (st.hasMoreElements()) {
67: String s = st.nextToken();
68: if (!isLegalJavaIdentifier(s))
69: return false;
70: }
71: return true;
72: }
73:
74: /**
75: * Ckecks if a string is a valid Java package identifier.
76: *
77: * @param string
78: * the string to be tested
79: */
80: public static boolean isLegalJavaExecutableIdentifier(String string) {
81: if (string == null)
82: return false;
83: if (string.equals("<init>"))
84: return true;
85: return isLegalJavaIdentifier(string);
86: }
87:
88: }
|