Mahdi
Mahdi

Reputation: 249

Reflection in Java (distinguishing two types)

In my program I'm passing 2 strings to some method for an evaluation. The method has to get the Class class for these strings(if it's a real class name!) and compare for their commonalities. There can be 2 type of inputs for strings:

  1. A Class name in Java API like "java.lang.Byte","java.lang.Math", etc.
  2. Any other string possible like "some string", "hello", etc.

in my method which gets these two strings how could I understand whether it is of type 1 or 2 so not to get Exception?

Upvotes: 0

Views: 104

Answers (2)

Vamsi Mohan Jayanti
Vamsi Mohan Jayanti

Reputation: 666

I doubt if there is a perfect condition to check this as "Hello" is as good a valid class name as java.lang.Byte. What you can do is validate string against the valid java identifiers http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8

So two checks : 1. Check for valid java class name. 2. Try Class.forName() to load the class. This will throough ClassNotFoundException if the class doesn't exist in the class path.

Have used a simple regex that I found in some other links to validate class name

String regexForBasicClassNameValidation = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*" ;
     if(inputString.matches(regexForBasicClassNameValidation))
     {
     try {
            Class.forName(inputString) ;
            System.out.println("Valid class name");
    } catch (ClassNotFoundException e) {
        System.out.println("Invalid Class name or class not found in classpath ");

    }
     }
     else
     {
     System.out.println("Not a class name");
     }

Upvotes: 2

Brian Roach
Brian Roach

Reputation: 76888

JavaDoc for Class.forName()

Class clazz = null;
try 
{
    clazz = Class.forName(myString);    
} 
catch (ClassNotFoundException e) 
{
    System.out.println("This isn't a class");
}

Upvotes: 1

Related Questions