开发者

Create Class objects based on type signature

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?

Edit

Thanks for your answers, it's not a surprise that Class.forName works pretty well with the wrapper classes. But I'm looking for a solution for all java types, including arrays and primitives. Thus my first line is not a typo. Some method signatures do have java primit开发者_开发知识库ives as parameters, I can't just use a wrapper class to reflect the method in a library, I really need the Class object for that type (like boolean).

Class<boolean> booleanClassObject = boolean.class;

works fine, as well as

String name = boolean.class.getName();


Perhaps you have a number of ifs:

if (type.equals("boolean")) {
    return boolean.class;
} else if (type.equals("int")) {
    return int.class;
} .. etc


The following will work:

Class.forName(Boolean.class.getName());

Auto(un)boxing should handle the translation to actual primitive. Although without seeing more of your code I can't be sure if this solves your problem.


It might be easier to actually create an array, and then ask for its .class. That's what I've done in the past.


Can you try using the Boolean wrapper class instead of the primitive boolean?


You are using boolean which is a primitive in java. You must use Boolean which is wrappaer class in java.


primitive type is a object and  not a class.  it can't getClassLoader and  getClassName.
the below expression will be wrong.
boolean a = new boolean();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜