I'm creating a system to save and load objects from disk. I made a Savable interface that includes methods to read and write data, and that works correctly. Anything in my program that needs to be saved can implement this interface and use it to save and read whatever data they need to work with. The problem lies in actually creating the objects when reading them from disk. Right now, I save the class name of the objects, and then when reading them I instantiate them using Class.forName(savedClassName).newInstance();. The problem with this is it requires any Savable class to have a no-argument constructor, but there is no way to force that in the interface itself. So if I, or someone working with me, tries to create a Savable object but forgets to include a no-arg constructor, there's going to be exceptions way down the line, and we very likely won't even discover them for a long time. I am at a loss to solve this problem, since it seems there is no way to use an interface to require a predictable way to construct an object.
-
Have you tried with an Abstract class instead (or plus) the Interface?Martin– Martin2013-11-22 09:59:36 +00:00Commented Nov 22, 2013 at 9:59
-
1Any reason why you didn't go with Serializable and an Object input/output stream?Ash– Ash2013-11-22 10:01:04 +00:00Commented Nov 22, 2013 at 10:01
-
@Martin: An Abstract class would be pretty restrictive (no other class hierarchies allowed)Ash– Ash2013-11-22 10:02:14 +00:00Commented Nov 22, 2013 at 10:02
-
@Martin I don't understand how using an abstract class would solve my problem.suddjian– suddjian2013-11-22 10:09:03 +00:00Commented Nov 22, 2013 at 10:09
-
@Ash, it depends on what they really need. If they need to be flexible with hierarchies, then they will have to check another solution.Martin– Martin2013-11-22 10:09:07 +00:00Commented Nov 22, 2013 at 10:09
|
Show 5 more comments
2 Answers
How about disallowing classes without a default constructor, to be saved. That way the only class anyone will ever try to load is one which has been saved and hence therefore one which has a default constructor.
1 Comment
suddjian
That's a good way to reduce the possible damage, but it still doesn't solve the problem that you have to just remember to include a no-args constructor every time you implement Savable.
You could potentially create an Abstract Unit test that tests for the presence of the default constructor (and nothing else) and inherit your unit tests from that, this is probably less restrictive than an abstract class in you hierarchy and this should indicate that the Constructor is missing.