简体   繁体   English

在子类中强制执行toString()实现

[英]Force toString() implementation in subclasses

I have an abstract parent class, and I would like it to force all subclasses to implement toString() method. 我有一个抽象的父类,我希望它强制所有子类实现toString()方法。

However putting: 但是放:

public abstract String toString();

is causing a compilation error: 导致编译错误:

Repetitive method name/signature for method 'java.lang.String toString()' in class ...

I believe this might be caused by groovy already having toString defined. 我相信这可能是由已经定义了toString的groovy引起的。

Thanks 谢谢

This works for me. 这适合我。 Is this new or did others just miss it? 这是新的还是别人错过了?

public abstract class Filterable
{
  @Override
  public abstract String toString();
}

public class ABC extends Filterable
{
  // Won't compile without toString();
}

The toString() is part of the java.lang.Object class which already has a default implementation for it. toString()java.lang.Object类的一部分,它已经有一个默认的实现。 So you essentially can't force the sub-classes to implement it. 所以你基本上不能强迫子类实现它。 If you want to force this kind of behavior (not sure why) then you can do something like below 如果你想强迫这种行为(不确定为什么)那么你可以做类似下面的事情

public class abstract SuperClass {
  public abstract String myToString();

  public String toString() {
    return myToString();
  }
}

Short answer: Isn't possible. 简答:不可能。 Long answer: You could try get around this by doing the following instead, implement in the parent class: 答案很长:您可以通过执行以下操作来尝试解决此问题,在父类中实现:

public final String toString() {
    getString();
}

public abstract String getString();

This causes the child class to need to implement the "getString()" method. 这会导致子类需要实现“getString()”方法。 However, the child of the child (grandchild) class has no guarantee of being forced to implement that method if the child class implements the "getString()" method. 但是,如果子类实现“getString()”方法,则子(孙)类的子项无法保证被强制实现该方法。 Example: 例:

A is the parent class, with the getString() method.
B extends A, and implements the getString() method.
C extends B, doesn't have to implement the getString() method.

Hope that helps :) 希望有帮助:)

You can write a unit test which will locate all classes extending your abstract class and verify that they declare toString(). 您可以编写一个单元测试,它将找到扩展抽象类的所有类,并验证它们是否声明了toString()。 To scan you can use Reflections library: 要扫描,您可以使用Reflections库:

  @Test
  public void validateToString() {
    final Reflections dtoClassesReflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("my.base.package"))
      .filterInputsBy(new FilterBuilder()
        .include(".*Dto.*") // optionally filter only some particular classes
        .exclude(".*Test.*")) // exclude classes from tests which will be scanned as well
      .setScanners(new SubTypesScanner(false)));

    final Set<Class<?>> allDtoClasses = dtoClassesReflections.getSubTypesOf(YourAbstractClass.class); // you set your class here (!!). You can set Object.class to get all classes

    allDtoClasses.forEach(dtoClass -> {
      logger.info("toString() tester testing: " + dtoClass);

      try {
        dtoClass.getDeclaredMethod("toString");
      } catch (NoSuchMethodException e) {
        fail(dtoClass + " does not override toString() method");
      }
    });


  }

你不能强制它们覆盖toString(),但你可以在抽象父类中使用toString()调用另一个抽象方法youGottaOverideToString(),这些子类必须实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM