Annotations
定义annotation类型
1.public @interface xxxxx{ //以@interface 表明这是一个annotation 类型
int id(); //每个方法都是该annotation的一个element,不得有参数和抛出异常。
String syposis();//返加类型:原始类型及String Class,enums annotations 及以这些类型作为基本类型的数组。
String engineer() default "[unassigned]";//可以设定默认值。
}
使用:
@xxxxx(
id = 33,//每个element都以","分隔。
syposis = "Enable dddd",
engineer = "xxxx" //最后结尾没有符合。
) //一般放在public static final等限定符前面。
public static void someMethod(){ }
<!--[if !supportEmptyParas]--> <!--[endif]-->
2.没有element 的annotation
public @interface xxNoElement{}
使用时可以省去后面的括号。
@xxNoElement() //也可以是@xxNoElement
public void someMethod(){}
<!--[if !supportEmptyParas]--> <!--[endif]-->
3.如果只有一个element 这个element的名称必须是value.
public @interface xxOneElement{
String value();
}
使用:
@xxOneElement( value = "vvvv")
//也可以是:@xxOneElement("vvvvvv")
public Class getSomeClass(){}
<!--[if !supportEmptyParas]--> <!--[endif]-->
在定义一个annotation时也可指定该annotation使用位置(method,field constructor package等)以及应该保持多长时间。
@Retention (RetentionPolicy.RUNTIME) //CLASS,RUNTIME,SOURCE
@Target (ElementType.METHOD) //ANNOTATION_TYPE,CONSTRUCTOR,FIELD,LOCAL_VARIBALE,METHOD,PACHAGE,PARAMETER,TYPE
public @interface xxxx{
}
<!--[if !supportEmptyParas]--> <!--[endif]-->
运用@annotation
import java.lang.reflect.*;
<!--[if !supportEmptyParas]--> <!--[endif]-->
public class RunTests {
public static void main(String[] args) throws Exception {
int passed = 0, failed = 0;
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class)) {
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("Test %s failed: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d%n", passed, failed);
}
}
本文深入解析Java注解的定义与使用方法,包括注解类型、元素、默认值设定及其在不同场景的应用。通过实例演示如何创建自定义注解并利用反射进行处理。
214

被折叠的 条评论
为什么被折叠?



