2

I want to create a method that constructs an object of a class received as a parameter much like the following one:

public static <T extends MyAbstractClass> T makeObject(Class<T> c){
    ObjectReceivedFromService orfs = getObjectFromService();
    Constructor<T> constr = c.getConstructor(ObjectReceivedFromService.class);
    return constr.newInstance(orfs);
}

Is there a way to make sure that this specific constructor exists on compile time? I would also like to use an interface instead of an abstract class if possible.

Thank you

Emroy
  • 85
  • 10

1 Answers1

2

You could expect not the class but the constructor itself as the parameter:

public static <T extends AnyInterface> T makeObject(Function<ObjectReceivedFromService, T> constructor){
    ObjectReceivedFromService orfs = getObjectFromService();
    return constructor.apply(orfs);
}

To call the Method:

makeObject(MyImplementation::new)

Finally, any constructor can be used as a function by using the method handle to the constructor.

David Ibl
  • 901
  • 5
  • 13