Twerterus Twerterus - 29 days ago 4
JSON Question

Convert string value to type

Say I have an object, and I'm storing all of it's attributes as pure JSON. Is there a way to store the .getClass() value in such a way as to be able to retrieve it and get the original object?

Ex:

class foo
{
int test;
String classType;
}


//other class
foo demo = new foo();
demo.classType = demo.getClass().toString();


//I'm not entirely sure how to convert classType into a type I can use to parse back the data, like so:
foo demo2 = (demo.classType)jsonData;


As this may be a bit of a broad question, I will accept an answer which just tells me what the above is called (a search term if you will).

Answer

Have a look at Class.forName(), Class.getName() and Class.newInstance().

The code could be something like (not tested):

String className = foo.geClass().getName();

Class<?> cls = Class.forName(className);
Object newFoo = cls.newInstance();