Java 接口是否可以定义为只有 Enum 可以扩展它?

我想这样做并没有什么特别的原因——我只是想知道这是否可能。如果有帮助的话,这是一个可以使用它的虚构情况:


想象一种类型Enum用作只读数据源,这样每个值都Enum包含不同的内容。器物。Enum_ Readable现在,假设我们需要一个将 的所有值读取Enum到单个缓冲区中的方法。这可以作为辅助类中的静态实用方法来实现(见下文)。


public class ReadableEnumUtils {

    /** reads data from all enum values into the charbuffer */

    public static <T extends Enum<T> & Readable> int readAll(Class<T> clazz, CharBuffer cb) throws IOException {

        int total = 0;

        for (T e : clazz.getEnumConstants()) {

            int intermediate = e.read(cb);

            if (intermediate < 0) {

                throw new IllegalArgumentException("The enum value \'" + e.name() + "\' had no data to read.");

            }

            total += intermediate;

        }

        return total;

    }

}

最好在接口中声明该方法,但这可能会造成混淆,因为非 Enum 类不应实现此类方法并不是立即显而易见的。理想情况下,接口的定义方式可以使编译器确保它仅由 的子类实现Enum。以下是该界面的示例:


interface ReadableEnum extends Readable {

    int read(CharBuffer cb) throws IOException;


    int readAll(CharBuffer cb) throws IOException;

}

我认为不可能让编译器确保ReadableEnum仅由子类实现Enum- 这是正确的吗?


炎炎设计
浏览 77回答 2
2回答

慕森卡

Java 默认情况下不支持类似的功能,您会问为什么不提供规范链接,但没有特殊原因,只是没有人决定添加这样的功能,您可以自己提出 - 但随后您可能会了解到它们不认为这是需要的,并且不会将其添加到语言中。但是java提供了非常强大的选项来自行实现这一点:注释处理。我创建了带有注释的简单 java 8 maven 项目:@Target(ElementType.TYPE)@Retention(RetentionPolicy.CLASS)public @interface EnumInterface {}并配有特殊处理器import javax.annotation.processing.*;import javax.lang.model.SourceVersion;import javax.lang.model.element.*;import javax.lang.model.type.*;import javax.lang.model.util.Types;import javax.tools.Diagnostic;import java.util.*;@SupportedAnnotationTypes("com.gotofinal.enuminterface.EnumInterface")@SupportedSourceVersion(SourceVersion.RELEASE_8)public class EnumInterfaceProcessor extends AbstractProcessor {&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {&nbsp; &nbsp; &nbsp; &nbsp; Messager messager = processingEnv.getMessager();&nbsp; &nbsp; &nbsp; &nbsp; Types typeUtils = processingEnv.getTypeUtils();&nbsp; &nbsp; &nbsp; &nbsp; // first we scan for all interfaces marked with this annotation&nbsp; &nbsp; &nbsp; &nbsp; List<TypeElement> enumOnlyInterfaces = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; for (Element rootElement : roundEnv.getRootElements()) { // getRootElements should return all types being compiled&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (! (rootElement instanceof TypeElement)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TypeMirror typeMirror = rootElement.asType();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // we check if this class have our annotation, we could also here check if this is an interface (by checking if it does not extend Object directly) and throw error otherwise&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (rootElement.getAnnotation(EnumInterface.class) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; enumOnlyInterfaces.add((TypeElement) rootElement);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // and now we scan for any non enum types that implement this interface&nbsp; &nbsp; &nbsp; &nbsp; for (Element rootElement : roundEnv.getRootElements()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (! (rootElement instanceof TypeElement)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TypeElement type = findImplementedInterface(rootElement.asType(), enumOnlyInterfaces, typeUtils);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (type == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (! (rootElement.asType() instanceof DeclaredType)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // it's fine if it is an enum&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.isEnum(rootElement.asType(), typeUtils)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // and we print error to compiler&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messager.printMessage(Diagnostic.Kind.ERROR, "Interface " + type.getQualifiedName()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+ " can't be used on non enum class: " + ((TypeElement) rootElement).getQualifiedName());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; public TypeElement findImplementedInterface(TypeMirror type, List<TypeElement> interfaces, Types types) {&nbsp; &nbsp; &nbsp; &nbsp; for (TypeElement anInterface : interfaces) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // types.isSubtype(typeA, typeA) would return true, so we need to add this equals check&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!anInterface.asType().equals(type) && types.isSubtype(type, anInterface.asType())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return anInterface;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; // maybe there is better way to do this... but I just scan recursively for a subtype with java.lang.Enum name, so it's not perfect but should be enough.&nbsp; &nbsp; public boolean isEnum(TypeMirror type, Types types) {&nbsp; &nbsp; &nbsp; &nbsp; for (TypeMirror directSupertype : types.directSupertypes(type)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TypeElement element = (TypeElement) ((DeclaredType) directSupertype).asElement();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (element.getQualifiedName().contentEquals("java.lang.Enum")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (isEnum(directSupertype, types)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}并将其注册到META-INF/services/javax.annotation.processing.Processor文件中:com.gotofinal.enuminterface.EnumInterfaceProcessor这段代码可能可以改进很多,我以前从未编写过任何注释处理器。但是当我们创建另一个 Maven 项目并将其声明为依赖项并编写如下代码时:@EnumInterfaceinterface TestInterface {}enum TestEnum implements TestInterface {}class TestClass implements TestInterface {}我们将无法编译它并出现错误:接口 com.gotofinal.enuminterface.TestInterface 不能用于非枚举类:com.gotofinal.enuminterface.TestClass

胡子哥哥

如果接口的所有实现都扩展某个类,则该接口的所有实例也是该类的实例;因此,此接口还必须扩展此类。由于接口声明的 extends 子句中的每个类型都必须是接口类型,因此您不能使接口扩展Enum 类;因此,您无法阻止非枚举类实现您的接口。您甚至无法通过替换来实现它,interface ReadableEnum extends Enum因为abstract class ReadableEnum extends Enum枚举类型不得声明为抽象。但是您仍然可以通过使其扩展由所有公共方法组成的接口来使其更难实现ReadableEnum非枚举类:IEnumEnumpublic interface IEnum<E extends Enum<E>> extends Comparable<E> {    String name();    int ordinal();    Class<E> getDeclaringClass();}interface ReadableEnum<E extends Enum<E> & ReadableEnum<E>> extends Readable, IEnum<E> {    int read(CharBuffer cb) throws IOException;    default int readAll(CharBuffer cb) throws IOException {        return ReadableEnumUtils.readAll(getDeclaringClass(), cb);    }}现在枚举可以ReadableEnum只通过实现read方法来实现,而其他类也必须实现name、ordinal、getDeclaringClass和compareTo。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java