在学习完java.lang包提供的3个基础注解之后,我们就可以学习自定义注解了。
下面就是一个简单的自定义注解类,我将和大家分享其中的细节。
注解类支持的的类型有:
8种基本数据类型,
枚举类型,
Class类型,
注解类型,
以及上面所有类型的数组.我在下面的代码中只使用了int类型的数组,别的类型的数组也是支持,大家可以自己测试一下.可能还有我不知道的类型,欢迎大家留言告诉我.大家共同进步.
下面的这个类就是今天的主角了.自定义注解类:
package com.mari.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MariAnnotation {
//String
String value();
//int[]
int[]arrayAttr() default {1, 2, 3};
//enum
MariType type() default MariType.A;
//Annotation
MetaAnnotation annotationAttr() default @MetaAnnotation("value");
//Class
Class<?> classAttr() default String.class;
}
- 注解类中使用到的枚举:
package com.mari.annotation;
public enum MariType {
A(10) {
@Override
public String Name() {
return "a";
}
},
B(20) {
@Override
public String Name() {
return "b";
}
},
C(30) {
@Override
public String Name() {
return "c";
}
};
private int number;
MariType(int number) {
this.number = number;
}
public abstract String Name();
}
- 注解类中使用到的注解类:
package com.mari.annotation;
public @interface MetaAnnotation {
String value();
}
- 下面这个是测试类:
package com.mari.annotation;
import java.lang.reflect.Method;
//数组的值如果只有一个的话可以省略大括号
//如果只有一个value属性需要设值, 可以省略 value=
@MariAnnotation(value = "abc", arrayAttr = 2, type = MariType.B,
annotationAttr = @MetaAnnotation("abc"),
classAttr = Integer.class)
public class AnnotationTest {
@MariAnnotation("qwe")
public static void main(String[] args) throws Exception{
if (AnnotationTest.class.isAnnotationPresent(MariAnnotation.class)) {
MariAnnotation annotation = AnnotationTest.class.getAnnotation(MariAnnotation.class);
System.out.println(annotation.value());
System.out.println(annotation.type().Name());
System.out.println(annotation.arrayAttr().length);
System.out.println(annotation.annotationAttr().value());
System.out.println(annotation.classAttr().getName());
}
System.out.println();
System.out.println("====================================");
System.out.println();
Method method = AnnotationTest.class.getMethod("function", null);
if (method.isAnnotationPresent(MariAnnotation.class)) {
MariAnnotation annotation = method.getAnnotation(MariAnnotation.class);
System.out.println(annotation.value());
System.out.println(annotation.type().Name());
System.out.println(annotation.arrayAttr().length);
System.out.println(annotation.annotationAttr().value());
System.out.println(annotation.classAttr().getName());
}
}
@MariAnnotation("function")
public void function(){
}
}
- 测试类输出的结果:
abc
b
1
abc
java.lang.Integer
====================================
function
a
3
value
java.lang.String
- 注解的详细语法可以通过java的语言规范了解,即看java的language specification
- 好了,这个就是java注解的基本使用了。大家有什么不理解的地方可以留言,我会尽力解答的。