Java注解
来源:互联网 发布:淘宝达人发布帖子 编辑:程序博客网 时间:2024/06/06 12:51
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();
}
- Java注解-自定义注解
- Java注解----自定义注解
- Java注解自定义注解
- Java注解--四种元注解
- Java注解-三种內建注解
- 【Java】【注解】自定义注解
- java注解
- java注解
- java注解
- java 注解
- Java注解
- java 注解
- Java 注解
- Java注解
- java 注解
- JAVA注解
- Java注解
- Java注解
- 泛型
- 利用D3DQUERY实现简单的GPU计时器
- poj 2917 Diophantus of Alexandria
- FusionChartsFree免费的报表
- JS去除空格格
- Java注解
- JavaScript重定向
- Hyperic HQ 可视化工具插件 WMV
- 经验点滴
- 在Ubuntu安装完成后更改默认的语言LANG,出现Cannot set LC_CTYPE to default locale: No such file or directory错误的解决办法
- 一个简单makefile(指定obj文件位置)
- MYSQL添加新用户 MYSQL为用户创建数据库 MYSQL为新用户分配权限
- PDF转word(图片转word)简单方法
- JAVA线程中的run 和start方法