Is it possible to save a Java Class<?> file?

2019-06-24 07:38发布

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?

3条回答
smile是对你的礼貌
2楼-- · 2019-06-24 08:14

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-06-24 08:18

I learned about Serialization from this website. It teaches the concept well. I recommend starting there.

查看更多
可以哭但决不认输i
4楼-- · 2019-06-24 08:20

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.

查看更多
登录 后发表回答