2 回答

TA貢獻1806條經(jīng)驗 獲得超8個贊
Java 默認情況下不支持類似的功能,您會問為什么不提供規(guī)范鏈接,但沒有特殊原因,只是沒有人決定添加這樣的功能,您可以自己提出 - 但隨后您可能會了解到它們不認為這是需要的,并且不會將其添加到語言中。
但是java提供了非常強大的選項來自行實現(xiàn)這一點:注釋處理。
我創(chuàng)建了帶有注釋的簡單 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 {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Messager messager = processingEnv.getMessager();
Types typeUtils = processingEnv.getTypeUtils();
// first we scan for all interfaces marked with this annotation
List<TypeElement> enumOnlyInterfaces = new ArrayList<>();
for (Element rootElement : roundEnv.getRootElements()) { // getRootElements should return all types being compiled
if (! (rootElement instanceof TypeElement)) {
continue;
}
TypeMirror typeMirror = rootElement.asType();
// 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
if (rootElement.getAnnotation(EnumInterface.class) != null) {
enumOnlyInterfaces.add((TypeElement) rootElement);
}
}
// and now we scan for any non enum types that implement this interface
for (Element rootElement : roundEnv.getRootElements()) {
if (! (rootElement instanceof TypeElement)) {
continue;
}
TypeElement type = findImplementedInterface(rootElement.asType(), enumOnlyInterfaces, typeUtils);
if (type == null) {
continue;
}
if (! (rootElement.asType() instanceof DeclaredType)) {
continue;
}
// it's fine if it is an enum
if (this.isEnum(rootElement.asType(), typeUtils)) {
continue;
}
// and we print error to compiler
messager.printMessage(Diagnostic.Kind.ERROR, "Interface " + type.getQualifiedName()
+ " can't be used on non enum class: " + ((TypeElement) rootElement).getQualifiedName());
}
return false;
}
public TypeElement findImplementedInterface(TypeMirror type, List<TypeElement> interfaces, Types types) {
for (TypeElement anInterface : interfaces) {
// types.isSubtype(typeA, typeA) would return true, so we need to add this equals check
if (!anInterface.asType().equals(type) && types.isSubtype(type, anInterface.asType())) {
return anInterface;
}
}
return null;
}
// 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.
public boolean isEnum(TypeMirror type, Types types) {
for (TypeMirror directSupertype : types.directSupertypes(type)) {
TypeElement element = (TypeElement) ((DeclaredType) directSupertype).asElement();
if (element.getQualifiedName().contentEquals("java.lang.Enum")) {
return true;
}
if (isEnum(directSupertype, types)) {
return true;
}
}
return false;
}
}
并將其注冊到META-INF/services/javax.annotation.processing.Processor文件中:
com.gotofinal.enuminterface.EnumInterfaceProcessor
這段代碼可能可以改進很多,我以前從未編寫過任何注釋處理器。但是當我們創(chuàng)建另一個 Maven 項目并將其聲明為依賴項并編寫如下代碼時:
@EnumInterface
interface TestInterface {}
enum TestEnum implements TestInterface {}
class TestClass implements TestInterface {}
我們將無法編譯它并出現(xiàn)錯誤:
接口 com.gotofinal.enuminterface.TestInterface 不能用于非枚舉類:com.gotofinal.enuminterface.TestClass

TA貢獻1825條經(jīng)驗 獲得超6個贊
如果接口的所有實現(xiàn)都擴展某個類,則該接口的所有實例也是該類的實例;因此,此接口還必須擴展此類。
由于接口聲明的 extends 子句中的每個類型都必須是接口類型,因此您不能使接口擴展Enum
?類;因此,您無法阻止非枚舉類實現(xiàn)您的接口。
您甚至無法通過替換來實現(xiàn)它,interface ReadableEnum extends Enum
因為abstract class ReadableEnum extends Enum
枚舉類型不得聲明為抽象。
但是您仍然可以通過使其擴展由所有公共方法組成的接口來使其更難實現(xiàn)ReadableEnum
非枚舉類:IEnum
Enum
public 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);
? ? }
}
現(xiàn)在枚舉可以ReadableEnum只通過實現(xiàn)read方法來實現(xiàn),而其他類也必須實現(xiàn)name、ordinal、getDeclaringClass和compareTo。
添加回答
舉報