Skip to content

Instantly share code, notes, and snippets.

@suxiaogang
Created June 12, 2014 09:05
Show Gist options
  • Save suxiaogang/5702c007af8702766557 to your computer and use it in GitHub Desktop.
Save suxiaogang/5702c007af8702766557 to your computer and use it in GitHub Desktop.
validated Identifier
/**
* 判断输入的字符串是否为Java保留的关键字
* @date 2013-08-05
* 不合法时返回true;
* 校验通过返回false;
*/
public static boolean validateReservedKeywords(String inputString) {
boolean flag = false;
final String[] keywords =
{"abstract", "continue", "for", "new", "switch", "assert", "default", "if",
"package", "synchronized", "boolean", "do", "goto",
"private", "this", "break", "double", "implements",
"protected", "throw", "byte", "else", "import", "public",
"throws", "case", "enum", "instanceof", "return",
"transient", "catch", "extends", "int", "short", "try",
"char", "final", "interface", "static", "void", "class",
"finally", "long", "strictfp", "volatile", "const",
"float", "native", "super", "while"};
// check if identifier is a java keyword
for (String s : keywords) {
if (s.equalsIgnoreCase(inputString)) {
flag = true;
break;
}
}
return flag;
}
/**
* 判断输入的字符串是否为Java合法的标识符命名规则
* @date 2013-08-05
* 不合法时返回true;
* 校验通过返回false;
*/
public static boolean validatedIdentifier(String inputString) {
boolean flag = false;
int c = 0;
try {
if (Character.isJavaIdentifierStart(inputString.charAt(0))) {
c++;
}
for (int i = 1; i < inputString.length(); i++) {
if (Character.isJavaIdentifierPart(inputString.charAt(i))) {
c++;
}
}
} catch (StringIndexOutOfBoundsException e) {
return true;
} finally {
if (c != inputString.length()) {
flag = true;
}
}
return flag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment