I have a program in which I need to store a Class object into memory by casting it into String. Is it possible to convert the String back into the original Class so that I can use that class variables? I am doing this in JAVA.
Example: test.java
class hello{
public String h1;
public String h2;
}
public class test {
public static void main(String[] args)
{
hello h = new hello();
h.h1 = "hello";
h.h2 = "world";
String s = h.toString();
System.out.println("Print s : "+s);
// Now I need to convert String s into type hello so that
// I can do this:
// (hello)s.h1;
// (hello)s.h2;
}
}
NOTE: this is not a homework, this is a personal project and I would be grateful if anyone can help!
Thanks!
Ivar
I think what you want to do is Serialization. I’m confused by your comment:
You can’t just cast String objects to arbitrary class types. Maybe you can elaborate on what you’re trying to accomplish here. If you want to be able to “save” a class to a file, then read it back in as an object, you want Serialization. Like this:
It can get more complicated when your fields are more complex classes than String. Implementing Serializable is just a “marker” interface that says that the object can be serialized, it doesn’t require any methods to be implemented. Your simple class just needs to be written out using an ObjectOutputStream and can be read back in using an ObjectInputStream.