Reputation: 249
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:
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
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
Reputation: 76888
Class clazz = null;
try
{
clazz = Class.forName(myString);
}
catch (ClassNotFoundException e)
{
System.out.println("This isn't a class");
}
Upvotes: 1