Java指定子类构造函数签名

Java指定子类构造函数签名,java,inheritance,interface,abstract-class,Java,Inheritance,Interface,Abstract Class,我想创建一个方法,用于构造作为参数接收的类的对象,非常类似于以下方法: public static <T extends MyAbstractClass> T makeObject(Class<T> c){ ObjectReceivedFromService orfs = getObjectFromService(); Constructor<T> constr = c.getConstructor(ObjectReceivedFromServ

我想创建一个方法,用于构造作为参数接收的类的对象,非常类似于以下方法:

public static <T extends MyAbstractClass> T makeObject(Class<T> c){
    ObjectReceivedFromService orfs = getObjectFromService();
    Constructor<T> constr = c.getConstructor(ObjectReceivedFromService.class);
    return constr.newInstance(orfs);
}
公共静态T生成对象(c类){
ObjectReceivedFromService orfs=getObjectFromService();
构造函数Constructor=c.getConstructor(ObjectReceivedFromService.class);
返回constr.newInstance(orfs);
}
有没有办法确保这个特定的构造函数在编译时存在? 如果可能的话,我还希望使用接口而不是抽象类


谢谢

您可以期望的不是类,而是构造函数本身作为参数:

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

最后,通过使用构造函数的方法句柄,任何构造函数都可以用作函数。

是否要确保
Class
具有无参数构造函数?使用接口而不是
MyAbstractClass
应该不会有问题。
makeObject(MyImplementation::new)