I\'m trying to do this, but doesn\'t work:
public static Class loadIt(String name) throws Throwable {
return Class.forName(name);
}
assert foo.loadIt(\"int
We use or own simple method (Java 7+):
/**
* Return the java {@link java.lang.Class} object with the specified class name.
*
* This is an "extended" {@link java.lang.Class#forName(java.lang.String) } operation.
*
* + It is able to return Class objects for primitive types
* + Classes in name space `java.lang` do not need the fully qualified name
* + It does not throw a checked Exception
*
* @param className The class name, never `null`
*
* @throws IllegalArgumentException if no class can be loaded
*/
public static Class> parseType(final String className) {
switch (className) {
case "boolean":
return boolean.class;
case "byte":
return byte.class;
case "short":
return short.class;
case "int":
return int.class;
case "long":
return long.class;
case "float":
return float.class;
case "double":
return double.class;
case "char":
return char.class;
case "void":
return void.class;
default:
String fqn = className.contains(".") ? className : "java.lang.".concat(className);
try {
return Class.forName(fqn);
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Class not found: " + fqn);
}
}
}