I've had a look around but nothing seems to quite cover what I wish to do. Is it possible to save a Class<?>
instance object at run-time? If so how would I go about doing it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Have you gone through concept of serialization using java. this link will help you on your problem.
In short Java.lang.Serializable is your friend to do this.
I learned about Serialization from this website. It teaches the concept well. I recommend starting there.
This is a set of comments on Java Serialization rather than an answer. Just some info not (yet) in the other answers.
Serialization not only saves an object, it saves all the objects it references, directly and indirectly. This can be really cool, but you might write one little objectette and find you've unexpectedly created a 10MB file.
If there's a reference, however indirect, to an non-serializable object in the one you're writing, the write will throw an Exception.
If you're using a socket, reset the ObjectOutput stream regularly. Otherwise, every time an object is written other than the first time, all that gets sent is a reference to the original data. Send the same object with successive values of 1, 2, 3, 4, and 5, and the object read will have values of 1, 1, 1, 1, and 1. Also, without reset, memory usage will soar because both ObjectOutput and ObjectInput will keep pretty much everything sent in memory. (Though it will only keep one copy of each distinct object.)
Serialization doesn't work if a class changes between being written and being read. Clever work with Externalization can get around this, however. (And remember serialVersionUID if your IDE will let you forget.)
Externalization lets you write the code to serialize a class. This can be very useful. You can put in version numbers and check them and you can leave out data than isn't needed or can be recreated during the read. It takes more work than automatic serialization, though.
When doing an Externalization read, be aware that all references may refer to objects whose data has not yet arrived; you can't consistently sum amounts from a list of child objects, for instance. It might pay to call a method after readObject to set up values that need to be calculated. (It's often better to send redundant information than to recalculate it.)
I learned all this the hard way.