Java标签定义与接口类似。
MyTag.java
package tiger.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 用户自定义标签,带有成员变量的MyTag
* @author x
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTag {
String name();
int age();
}
编写测试MyTag的测试类TagTest。
TagTest.javapackage newpackage;
import java.lang.annotation.Annotation;
import tiger.annotation.MyTag;
/**
* 获取注释信息
* @author x
*/
public class TagTest {
@MyTag(name = "nihao", age = 5173)
public void test() {
}
public static void main(String args[]) {
TagTest tt = new TagTest();
try {
Annotation[] annotation = tt.getClass().getMethod("test").getAnnotations();
System.out.println("hi");
for(Annotation tag : annotation) {
System.out.println("Tag is:" + tag);
System.out.println("tag.name()" + ((MyTag)tag).name());
System.out.println("tag.age()" + ((MyTag)tag).age());
}
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
}
}
输出结果:
hiTag is:@tiger.annotation.MyTag(name=nihao, age=5173)
tag.name()nihao
tag.age()5173