annotation理解

--START

annotation是java5的新特性,中文通常翻译为“注解”,它与“注释”是不同的,基本区别在于“注释”是给程序员看的,“注解”是给编译器看的。

annotation主要的用途是提供给framework使用,framework根据java的反射机制提取到运行时annotation信息,根据这些信息可以灵活改变运行方式。(没有碰到需要使用annotation的场景,因此不好不理解)。framework指的是比如:struts/spring/hibernate等


我能理解annotation的用途是:如果在一个类方法前使用@Override,则表示该方法一定是对父类方法的改写,这时刚好把方法名字拼写错了,编译时,编译器将抛出一个错误。用途:避免笔误,防止以为自己改写了父类方法,其实由于拼写错误导致改写失败,后续使用时发生出乎意料的问题。


暂时看起来annotation对目前自身工作用处不大,了解到此处即可。


java se提供3个基本的annotation,定义在java.lang

  • @Override
  • @Deprecated
  • @SuppressWarnings
java提供4个Meta-annotation
  • @Target:Where this annotation can be applied. The possible ElementType arguments are:
    • CONSTRUCTOR: Constructor declaration
    • FIELD: Field declaration (includes enum constants) LOCAL_VARIABLE: Local variable declaration METHOD: Method declaration
      Annotations 763
    • PACKAGE: Package declaration
    • PARAMETER: Parameter declaration
    • TYPE: Class, interface (including annotation type),or enum declaration
  • @Retention:How long the annotation information is kept. The possible RetentionPolicy arguments are:
    • SOURCE: Annotations are discarded by the
      compiler.
    • CLASS: Annotations are available in the class file by the compiler but can be discarded by the VM.
    • RUNTIME: Annotations are retained by the VM at run time, so they may be read reflectively.
  • @Documented:Include this annotation in the Javadocs
  • @Inherited:Allow subclasses to inherit parent annotations


--END

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值