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
Post a Comment