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

扫描二维码关注公众号,回复: 10792445 查看本文章
发布了29 篇原创文章 · 获赞 0 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/levin_li/article/details/8522288