java - How to instantiate Class class for a primitive type? -


i'm trying this, doesn't work:

public static class loadit(string name) throws throwable {   return class.forname(name); } assert foo.loadit("int") == int.class; // exception here 

how should properly?

you can't, because primitives not objects.

what trying though not yet instantiation - loading class. can't primitives. int indeed name used int types, whenever class object obtained (via reflection, example method.getreturntype()), can't load forname().

reference: reflection tutorial:

if fully-qualified name of class available, possible corresponding class using static method class.forname(). this cannot used primitive types

a solution instantiate primitive use commons-lang classutils, can wrapper class corresponding given primitive:

if (clazz.isprimitive() {     clazz = classutils.primitivetowrapper(clazz); } clazz.newinstance(); 

note assumes have class representing int type - either via reflection, or via literal (int.class). beyond me usecase of having string representation of that. can use forname("java.lang.integer") instead.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -