在开发过程中,我有时会编写仍处于实验状态的类或方法。我想声明这些类,以便我可以直接在代码中看到它们。整个事情应该像 @Deprecated
一样工作。只是意义相反。
据我所知,Java中没有这样的声明。或者是吗? 如果不是:我如何实现此功能?
最佳答案
对于 Java 1.6+(不确定 1.5)你可以使用你自己的自定义注释,这里是一个你可以使用的功能模板:
package com.mycompany.annotations;
import java.lang.annotation.*;
/**
*
* This element has an experimental maturity. Use with caution.
*
*
* NOTE: The developers of this element is not responsible for the issues created,
* using it is not suggested for production environment. If you see this annotation do this, do not do that etc
* Enjoy responsibly....
*/
@Documented //this annotation maybe helpful for your custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE, ElementType.PACKAGE,
ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE, ElementType.TYPE_PARAMETER
})
public @interface Experimental {}
这里是ElementType
的源码,大家可能不想用ElementType.TYPE_USE,ElementType.TYPE_PARAMETER
元素
/*
....
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 4.1 The Kinds of Types and Values
*/
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
顺便说一下,这是我在搜索可能已实现实验性的库时从我的 IntelliJ 中看到的内容
有一个 Experimental
注释是用 Java 9 定义的。但请注意,它在 Oracle JDK 中,而不是 OpenJDK 中。在撰写本文时,您需要从官方站点安装 jdk-11 才能查看/使用它。由于 Stephen C. 列出的事实,我不会将它用于此目的。
无论如何你不能将它用于方法。因为它的源代码是
...
package jdk.jfr;
/*
...
*
* @since 9
*/
@MetadataDefinition
@Label("Experimental")
@Description("Element is not to be shown to a user by default")
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.TYPE })
public @interface Experimental {
}
关于java - 有没有办法在 Java 中将类/方法声明为实验性的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55402614/