簡體   English   中英

用於實施靜態變量或靜態方法的Java注釋?

[英]Java annotation for enforcing static variables or static methods?

我有興趣做這樣的事情:

public interface Foo {

  public static "abstract" Bar SOME_BAR; // subclasses define one of these

}

public interface Foo {

  public static "abstract" Baz buildABas(...); // subclasses define this method 

}

沒有靜態,這是OOP 101,但它不能在標准的oop java中完成。 我想知道是否有一個注釋可以確保這種行為?

編輯:

我有興趣指定一組選項來定義如何為“可配置”對象設置內容。 這可能是命令行標志等。

我猜你想要的是有一個像這樣的方法

public void callFoo(Class<?> clazz)

並且你想確保clazz有一個方法public static void foo()

我想了一會兒,想到的技術都沒有讓你到那里。 您可以使用AnnotationProcessor來確保使用特定注釋注釋的任何類具有特定方法或具有哪些方法(如果沒有,則生成編譯錯誤)但是無法確保(在編譯時)傳遞的Class參數callFoo(Class<?> clazz)用注釋注釋。

這是一個AnnotationProcessor,可以讓你到達那里:

import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;


@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes("so.Foo")
public class FooAnnotationProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {

        TypeElement foo = processingEnv.getElementUtils().getTypeElement("so.Foo");
        Set<? extends Element> classes = roundEnv.getElementsAnnotatedWith(foo);
        Messager messenger = processingEnv.getMessager();
        for (Element e : classes) {
            boolean found = false;
            for (Element method : e.getEnclosedElements()) {
                messenger.printMessage(Diagnostic.Kind.ERROR, 
                        method.getSimpleName());
                if (method.getKind() == ElementKind.METHOD && method.getSimpleName().toString().equals("getInstance")) {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                messenger.printMessage(Diagnostic.Kind.ERROR, 
                    "The following class does not implement getInstance : " + e.getSimpleName(),e);
            }
        }
        return true;
    }

}

最后,我建議您允許它在運行時強制執行或重新設計代碼,這樣您就不需要使用靜態方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM