我想创建一个方法来构造作为参数接收的类的对象,非常类似于以下方法:
public static <T extends MyAbstractClass> T makeObject(Class<T> c){
ObjectReceivedFromService orfs = getObjectFromService();
Constructor<T> constr = c.getConstructor(ObjectReceivedFromService.class);
return constr.newInstance(orfs);
}
有没有办法确保这个特定的构造函数在编译时存在? 如果可能的话,我还想使用接口(interface)而不是抽象类。
谢谢
最佳答案
您可能期望的参数不是类,而是构造函数本身:
public static <T extends AnyInterface> T makeObject(Function<ObjectReceivedFromService, T> constructor){
ObjectReceivedFromService orfs = getObjectFromService();
return constructor.apply(orfs);
}
调用方法:
makeObject(MyImplementation::new)
最后,通过使用构造函数的方法句柄,任何构造函数都可以用作函数。
关于Java指定子类构造函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274116/