java强制扩展类

在Java中,我可以以某种方式强制扩展抽象类的类来实现其构造函数,并将Object作为参数吗?

就像是

public abstract class Points { //add some abstract method to force constructor to have object. } public class ExtendPoints extends Points { /** * I want the abstract class to force this implementation to have * a constructor with an object in it? * @param o */ public ExtendPoints(Object o){ } } 

您可以在抽象类中使用带有参数的构造函数(如果要禁用匿名子类,请将其保护)。

 public abstract class Points{ protected Points(Something parameter){ // do something with parameter } } 

这样做会强制实现类具有显式构造函数,因为它必须使用一个参数调用超级构造函数。

但是,您不能强制覆盖类具有带参数的构造函数。 它总是可以伪造这样的参数:

 public class ExtendPoints extends Points{ public ExtendPoints(){ super(something); } } 

正如其他人之前所说的那样,构造函数的签名不会被强制执行,但您可以通过使用AbstractFactory模式来强制执行一组特定的参数。 然后,您可以定义工厂界面的create方法以获得特定签名。

没有构造函数不会被inheritance,因此除非您没有指定构造函数并获取默认的无参数构造函数,否则每个类都需要提供它自己的构造函数。

可能在编译时不可能,但是如果声明了所需的构造函数,则可以在运行时使用reflection来检查:

 public abstract class Points { protected Points() { try { Constructor constructor = getClass().getDeclaredConstructor(Object.class); if (!Modifier.isPublic(constructor.getModifiers())) throw new NoSuchMethodError("constructor not public"); } catch (SecurityException ex) { throw new RuntimeException(ex); } catch (NoSuchMethodException ex) { throw (NoSuchMethodError) new NoSuchMethodError().initCause(ex); } } } 

如果public Points(Object o) {}添加public Points(Object o) {}构造函数,则强制任何子类构造函数调用该超级构造函数。 但是,我认为没有办法确保子类使用那个确切的构造函数签名。

编辑

好吧,不,它不可能用参数强制执行构造函数。