Create Class objects based on type signature

Posted by Andreas_D on Stack Overflow See other posts from Stack Overflow or by Andreas_D
Published on 2010-03-17T11:00:57Z Indexed on 2010/03/17 11:11 UTC
Read the original article Hit count: 193

Filed under:
Class.forName(boolean.class.getName());

This doesn't work in Java - the virtual machine slaps you with a ClassNotFoundException. I was in need for something like that because I wanted to reflect methods based on Strings that included the method signatures, like

public void doSomething(boolean yesWeCan, java.lang.String[] presidents);

At the end I came up with a custom 'ClassFactory' which translates the type Strings to class objects. This factory includes a lot of handlers for primitive and array type values.

The handler for array type objects is something like:

if (isArrayOfObjects) {
   return Class.forName("L["+typeName.replace("[]", "")+";");
}

My question is - have I missed something in the Java 1.5+ API that might do the trick?

© Stack Overflow or respective owner

Related posts about java