Skip to main content

Does Java have a built in method to determine if an identifier is legal [Resolved]

Naming a variable or class, for example, must adhere to certain rules (such as not allowing keywords or reserved words as identifiers)

I really don't want to code my own method to do such a thing. Does java have something already built in?

My goal is that I am building an expression builder / code generator. It will recognize user specified variables and these must respect java's identifier rules or a warning is presented to user to rename his variable.


Question Credit: Constantin
Question Reference
Asked March 10, 2018
Tags: java
Posted Under: Programming
45 views
3 Answers

You'll want to look at JavaUtils.isJavaKeyword ... it's not part of the Java API though, it's part of Apache Axis:
http://axis.apache.org/axis2/java/core/api/org/apache/axis2/util/JavaUtils.html


credit: sjalexander
Answered March 10, 2018

Guess I will borrow from JavaUtils code then :)

static final Collator englishCollator = Collator.getInstance(Locale.ENGLISH);
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, englishCollator) >= 0);
     } 

credit: Constantin
Answered March 10, 2018

JJavaName in Sun's JCodeModel has the following method:

/**
 * Checks if a given string is usable as a Java identifier.
 */
public static boolean isJavaIdentifier(String s) {
    if(s.length()==0)   return false;
    if( reservedKeywords.contains(s) )  return false;

    if(!Character.isJavaIdentifierStart(s.charAt(0)))   return false;

    for (int i = 1; i < s.length(); i++)
        if (!Character.isJavaIdentifierPart(s.charAt(i)))
            return false;

    return true;
}

Unfortunately, the reservedKeywords field is private and there's no isReservedWord method, but if the goal is to validate a String as an identifier, this is ideal.


credit: megaflop
Answered March 10, 2018
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA