package com.yinbodotcc2.annotation;
public @interface AnnotationWithDefaultElementValue
{
int major();
//All default values must be compile-time constants
int minor() default 0;
double d() default 3.14;
//注意一下数组的默认值要用array initializer syntax
int[] x() default {1,2};
String s() default "hello";
String[] s2() default {"hello", "world"};
Class[] c2() default {String.class, Exception.class};
}
class TestIt
{
/**
默认值不会被编译进element中,For example, when you use @Version(major=2),
this annotation instance is compiled as is。In other words,
this annotation is not modified to @Version(major=2, minor=0) at the time of compilation
但是运行时如果你要取这个值,它会从annotation的类型定义中取出默认值。这样,当运行时if you change the default value
of an element, the changed default value will be read whenever a program attempts to read it
(这样是不是可以被利用以实现一些动态加载能力?)
*/
@AnnotationWithDefaultElementValue(major = 1)
public void test()
{
}
@AnnotationWithDefaultElementValue(major = 1, minor = 2)
public void test2()
{
}
//element要编译期为常量即可
@AnnotationWithDefaultElementValue(major = 1, minor = 2+3)
public void test3()
{
}
//element要编译期为常量即可
@AnnotationWithDefaultElementValue(major = 1, s="hello")
public void test4()
{
//@AnnotationWithDefaultElementValue(major = 1, s= new ("hello"))
System.out.println("new (\"hello\")不是编译期常量,所以会编译报错");
//you cannot use null as the value for any type of elements in an annotation
//@AnnotationWithDefaultElementValue(major = 1, s=null)
System.out.println("element 不能赋值为null");
}
}