Java注解
注解的应用结构图
问题1:.class文件是字节码还是二进制码?
答:(1)字节码文件本来就是二进制文件,所以.class文件是字节码文件,也是二进制文件。
问题2:Eclipse 是否一保存源文件就马上编译?是否是在编译时才检查语法错误,如果不是,为什么我们在正写代码的时候,没有保存,而eclipse工具依然会提示错误呢?
答:
注解的定义:
1. 语法
@Retention(RetentionPolicy)
@Target(ElementType)
public @interface MyAnnotation{}
2. @Retention(RetentionPolicy),即保留阶段,若不指定,则默认值为RetentionPolicy.CLASS;RetentionPolicy有三个:RetentionPolicy.SOURCE、RetentionPolicy.CLASS、RetentionPolicy.RUNTIME。
3. @Target(ElementType),即目标元素, ElementType有ElementType.TYPE, ElementType.METHOD, ElementTypeFIELD, ElementType.PACKAGE, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE
4. 使用反射检查注解是否在RUNTIME阶段,并测试获取注解的名称:
AnnotationTest.java:
import java.lang.annotation.*;
@MyAnnotation
public class AnnotationTest {
@MyAnnotation
public static void main(String[] args) {
if (AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@interface MyAnnotation {
}
5. 注解的属性:像接口一样定义
import java.lang.annotation.*;
@MyAnnotation("abc")
public class AnnotationTest {
public static void main(String[] args) {
if (AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation myAnnotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation );
System.out.println(myAnnotation.value());
System.out.println(myAnnotation.color());
System.out.println(myAnnotation.arrInt().length);
System.out.println(myAnnotation.direction().nextDirection());
System.out.println(myAnnotation.target());
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@interface MyAnnotation {
String value();
String color() default "red";
int [] arrInt() default {1,3,2};
Direction direction() default Direction.L;
Target target() default @Target(ElementType.TYPE);
}
enum Direction {
L(){
@Override
Direction nextDirection() {
return Direction.U;
}
},
U(){
@Override
Direction nextDirection() {
return Direction.R;
}
},
R(){
@Override
Direction nextDirection() {
return Direction.D;
}
},
D(){
@Override
Direction nextDirection() {
return Direction.L;
}
};
abstract Direction nextDirection();
}