Determining correctness of java identifier

Just a code snippet to have it available when I will look for it next time..

If you ever wanted to determine whether some string is (or can be) java class name and you don’t want call Class.forName(string) for some reasons, you can still check for syntax. When I googled for this, I found only “simple” character version and since java allows users to use UTF-8 in package and class names, this is just insufficient. Main idea is still the same thing – use Character.isJavaIdentifierStart and Character.isJavaIdentifierPart, but not for individual characters, but for code points (UTF-8 characters).

String[] identifiers = s.split("\\.");
for(String identifier : identifiers) {

    int i = 0;
    while(i < identifier.length()) {
        int codePoint = identifier.codePointAt(i);

         if(i == 0) {
                throw new IllegalArgumentException("...");
        } else {
                 throw new IllegalArgumentException("...");

        i += Character.charCount(codePoint);

// at this point, you know that s contains valid
// java identifier (its code I wrote for Jersey so
// you can modify it for example to return true
// or false or whatever..)

And final remark: You need at least JDK 1.5 to be able to do this. Enjoy :]

This entry was posted in java and tagged . Bookmark the permalink.

One Response to Determining correctness of java identifier

  1. Pingback: BILL

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>