I think Nappa has a good, practical answer. If you want to be a little fancier, you can check your class for membership in a hierarchy with isAssignableFrom()
on the Class
method.
The code below uses a built-in hierarchy (StringBuilder
implements the CharSequence
interface). When it finds a class of type CharSequence
, it casts the class and then calls length()
on it.
You can maintain control of your class types without throwing exceptions, which might be a little cleaner in some circumstances.
Note that this code still throws ClassNotFoundExcpetion
if you spell then name of a class incorrectly. You must still catch that exception.
public class ReflectionSubclassing
{
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
getDoubleValue( "java.lang.StringBuilder" );
getDoubleValue( "javax.swing.JButton" );
}
private static void getDoubleValue( String className )
throws ClassNotFoundException, InstantiationException,
IllegalAccessException
{
Class<?> tempClass = Class.forName( className );
if( java.lang.CharSequence.class.isAssignableFrom( tempClass ) ) {
Object charSeq = tempClass.newInstance();
CharSequence cs = (java.lang.CharSequence)charSeq;
System.out.println( cs.length() );
} else
System.out.println( "nope" );
}
}
Sample code output:
run:
0
nope
BUILD SUCCESSFUL (total time: 0 seconds)