Let's say I have a method that takes a very long time to create an object,
public class Foo implements Serializable {
public static Foo create(...){
/* (takes a long time) */
}
}
I also have a helper class that serializes and deserializes objects,
public class Pickle {
public static void dump(Serializable obj, String filename) {
/* ... */
}
public static Object load(String filename) {
/* ... */
}
}
I want a function that first attempts to load the serialized object specified by filename
, but if that fails, creates the object default
. It might look something like this:
public Object conditionalCreate(String filename, Object default)
{
Object obj = null;
try{
obj = Pickle.load(filename);
}
catch(Exception e){
obj = default;
}
return obj;
}
The way the conditionalCreate
function is written now, default
will always be created -- I only want to create the default
object if it's necessary.
In another language, the conditionalCreate
function might look like:
public Object conditionalCreate(String filename, Function defaultConstructor){
Object obj = null;
try{
obj = Pickle.load(filename);
}
catch(Exception e){
obj = defaultConstructor(); /* Note the difference here */
}
return obj;
}
Additionally, I'd like a way to pass arguments to this default constructor if construction of the object is necessary (if deserializing failed).
Is something like this possible in Java 7?