mercredi 5 août 2015

How do I pass varied parameters when constructing objects via reflection?

I have a situation where I use reflection to create objects at run-time based on their fully qualified class names. All the objects extend the same abstract class, so their general type is known at compile time but the concrete implementation is determined by the class name supplied at run-time.

The abstract class provides one static method named create, that takes the class name and other parameters with which to construct the concrete object. Each Response has an actual type A and a storage type S. The actual type is the "proper" representation of the data in Java and the storage type is the thing that gets stored in the database. E.g. A might be a Date object and S might be the same Date objected converted to a Long for storage in SQLite.

Here's a simplified representation:

public abstract class Response<A, S> {

    public Response(String clazz, Object value, boolean actual) {
        this.clazz = clazz;
        if (actual) {
           actualValue = (A) value;
        } else {
            actualValue = toActualValue((S) value);
        }
    }

    public static Response create(String clazz, Object value) {
        //create response by reflection
        return response;
    }
}

This was working okay until I now when I have to deal with the fact that in addition to the two parameters that each Response implementation takes, some Response implementations now need to take additional parameters.

These additional parameters cannot be passed via setter methods as they are typically used in the protected method toActualValue() that is called from within the abstract Response constructor.

I've considered using the Builder pattern to handler the optional parameters, but then I would need a way to determine which Response implementations take which parameters - and I can't think of a clean way to provide that information. Maybe I am thinking about this entirely wrong. Any helpful insights or suggestions will be appreciated.





Aucun commentaire:

Enregistrer un commentaire