Java注解

Java注解

注解的应用结构图


问题1:.class文件是字节码还是二进制码?

答:(1)字节码文件本来就是二进制文件,所以.class文件是字节码文件,也是二进制文件。

问题2Eclipse 是否一保存源文件就马上编译?是否是在编译时才检查语法错误,如果不是,为什么我们在正写代码的时候,没有保存,而eclipse工具依然会提示错误呢?

答:

注解的定义:

1. 语法

@Retention(RetentionPolicy)

@Target(ElementType)

public @interface MyAnnotation{}

2. @Retention(RetentionPolicy),即保留阶段,若不指定,则默认值为RetentionPolicy.CLASSRetentionPolicy有三个:RetentionPolicy.SOURCERetentionPolicy.CLASSRetentionPolicy.RUNTIME

3. @Target(ElementType),即目标元素, ElementTypeElementType.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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值