注释上的自定义Eclipse警告

假设我有一个内部方法,只能在某些情况下使用。

在Eclipse中,是否有可能将其标记为内部并在用于阻止我或将使用我的API的人误用而不知道他们正在做什么时显示警告。 我无法更改其可见性,因为它也可能在其他包/非扩展类中使用。

像这样的东西:

@Internal public void doSomeInternalStuff() { // ... } 

然后,在Eclipse中发出警告:

在此处输入图像描述

你明白了。

有希望吗?

JSR269 ( 可插入注释处理器API )允许您编写可以处理自定义注释的自定义注释处理器 ,并使您能够使用javax.annotation.processing.Messager打印错误或警告。 以下是一个例子。

 import java.util.Set; import javax.annotation.processing.AbstractProcessor; 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.TypeElement; import javax.tools.Diagnostic; @SupportedAnnotationTypes("fully.qualified.name.of.InternalAnnotationType") @SupportedSourceVersion(SourceVersion.RELEASE_6) public class CustomAnnotationProcessor extends AbstractProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { for (Element element : roundEnv.getElementsAnnotatedWith(InternalAnnotationType.class)) { InternalAnnotationType internalAnnotation = element.getAnnotation(InternalAnnotationType.class); String message = "The method " + element.getSimpleName() + " is marked internal and its use is discouraged"; processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message); } return true; } } 

在Eclipse中,您可以通过右键单击项目,然后选择Properties – > Java Compiler – > Annotation Processing – > Factory Path并添加包含自定义注释处理器的Jar,在Java Compiler中注册注释处理器。 这是一篇有趣的文章,解释了细节。

或者 ,您可以将所有“内部”方法API放在专用类中,并在Eclipse构建路径中为该类添加访问规则 ,以便项目中依赖于此类的任何代码都会显示警告。

阅读关于内部方法的内容Herbert Schildt的书“Java:beginers guide”在这里链接: http ://www.amazon.com/Java-Beginners-Guide-5th-Edition/dp/0071606327