强制继承链的每个类重写抽象方法 [英] Force every class of an inheritance chain to override an abstract method

查看:148
本文介绍了强制继承链的每个类重写抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个继承链,其中每个类通过添加一个新字段来扩展其超类,并且我希望该链的每个类都覆盖 toString()方法,如此:

Suppose I have an inheritance chain where every class extends its superclass by adding a new field and I want every class of that chain to override the toString() method like so:

public String toString()
{
    return super.toString() + "[newfield=" + newfield + "]";
}

如果我使用抽象基类,那么当继承链的一个类变为具体来说,通过实现抽象方法,从那时起所有子类都变得具体,通过继承已经实现的方法。

If I use an abstract base class then when a class of the inheritance chain becomes concrete by implementing the abstract method all the subclasses from that point on become concrete as well by inheriting the already implemented method.

Java中有没有办法强制每个类都要覆盖(重新实现)抽象方法,即使它已经在继承链中实现得更高了?

Is there a way in Java to force every class to override (reimplement) the abstract method even though it has already been implemented higher in the inheritance chain?

推荐答案

<回答简短:没有。

长答案:你可以编写一个扫描类路径的单元测试(使用像反思,加载抽象类的每个子类并使用反射检查方法。但是在编译时没有办法做到这一点。

Long answer: you could write a unit test that scans the class path (use a library like reflections for that), loads every subclass of the abstract class and checks for the method using reflection. But there's no way to do it at compile time.

除了Java,
AspectJ 有一个 hasMethod()切入点,可以为你做检查,但不幸的是,这只对声明父母的建议。也许你可以使用aspectj分两步完成:

Aside from Java, AspectJ has a hasMethod() pointcut, which could do the check for you, but unfortunately that's only valid for the declare parents advice. Perhaps you could do it in two steps using aspectj:


  • 定义一个接口 IllBehaved

  • 定义一个建议,将此接口分配给从基类扩展但没有成员的类

  • 然后声明实现此接口的所有类型的编译错误

  • define an interface IllBehaved.
  • define an advice that assigns this interface to classes that extend from your base class but don't have the member
  • then declare a compile error for all types that implement this interface

pointcut isSubTypeOfYourClass(): within(com.your.BaseClass+);
pointcut overridesMethod(): hasmethod(public void yourMethodName(..));
declare parents: isSubTypeOfYourClass() && !overridesMethod()
                 implements com.yourcompany.IllBehaved;
declare error: isSubTypeOfYourClass() && within(com.yourcompany.IllBehaved+):
                 "Implementation class must override <Foo> method";


我没有测试过这个,但它如果您打开 -XhasMember 选项,则应该可以正常工作。
当你使用Maven,Ant,Eclipse等标准工具时,很容易将aspectj集成到你的构建中。

I haven't tested this, but it should work if you turn on the -XhasMember option. And it's easy enough to integrate aspectj into your build when you use standard tools like Maven, Ant, Eclipse etc.

这篇关于强制继承链的每个类重写抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆