-1

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?

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • Yes, what is your exact problem? – jlordo Jun 27 '13 at 14:17
  • I think I'm pretty clear in my question about what my problem is. I'm looking for a way to do something. That something is explained in the question. Am I misunderstanding your comment? – jedwards Jun 27 '13 at 14:19
  • Make [java.lang.reflect.Constructor](https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Constructor.html) the type of the second parameter in method `conditionalCreate`. Or maybe [MethodHandle](https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandle.html) is appropriate? Or maybe even a [dynamic proxy](https://docs.oracle.com/javase/7/docs/technotes/guides/reflection/proxy.html) – Abra Jan 10 '21 at 11:54

1 Answers1

0

Not sure if this is what you mean because it seems fairly simple, but:

public <C> C conditionalCreate(String filename, Class<C> defaultType){
    try{
        //try to return loaded element
        return (C) Pickle.load(filename);
    }
    //if it fails log the error
    catch(Exception e){
        Logger.log("Exception happened", e);
    }
    return defaultType.newInstance();
}
darijan
  • 9,725
  • 25
  • 38
  • The problem with this approach is that I'd have to hard-code `Foo` into the method, I'm looking for a way to pass `Foo` and any necessary initialization arguments *to* this function. So that the function can be used more generally. – jedwards Jun 27 '13 at 14:27