如果你真的不想这样做..一种方法是以编程方式检查抽象类构造函数,即类中定义的方法是允许的方法.
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public abstract class Base {
private static final Set allowedMethodNames = new HashSet<>(Arrays.asList("doThis", "wait", "wait", "wait", "equals", "toString", "hashCode", "getClass", "notify", "notifyAll"));
public Base() {
Set allMethods = new HashSet<>();
for (Method aMethod : getClass().getMethods()) {
allMethods.add(aMethod.getName());
}
if (!allowedMethodNames.equals(allMethods)) {
allMethods.removeAll(allowedMethodNames);
throw new IllegalStateException("Following methods not allowed ");
}
}
public abstract void doThis();
}
public class Disallowed extends Base {
@Override
public void doThis() {
System.out.println("dooooooo");
}
public void doSomethingElse() {
System.out.println("not allowed");
}
public static void main(String[] args) {
new Allowed().doThis();
new Disallowed();
}
}
public class Allowed extends Base {
@Override
public void doThis() {
System.out.println("doing this");
}
}
当有人尝试创建“禁止”的实例时,它将失败.但是’new Allowed().doThis()’可以正常工作.
更优雅的方法是引入自定义注释注释处理器,并在编译期间执行相同的检查.