Annotations 注解

小结:

1)

 a particular variable in your program is never assigned to null; you want to avoid triggering a NullPointerException

 

 

 

    @Autowired

Lesson: Annotations (The Java™ Tutorials > Learning the Java Language) https://docs.oracle.com/javase/tutorial/java/annotations/

Lesson: Annotations

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

This lesson explains where annotations can be used, how to apply annotations, what predefined annotation types are available in the Java Platform, Standard Edition (Java SE API), how type annotations can be used in conjunction with pluggable type systems to write code with stronger type checking, and how to implement repeating annotations.

 

 

Answers to Questions and Exercises: Annotations (The Java™ Tutorials > Learning the Java Language > Annotations) https://docs.oracle.com/javase/tutorial/java/annotations/QandE/answers.html

Answers to Questions and Exercises: Annotations

Questions

  1. Question: What is wrong with the following interface:

    public interface House {
        @Deprecated
        public void open();
        public void openFrontDoor();
        public void openBackDoor();
    }
    

    Answer The documentation should reflect why open is deprecated and what to use instead. For example:

    open
    openFrontDoor
    openBackDoor
    
  2. Question: Consider this implementation of the House interface, shown in Question 1.

    public class MyHouse implements House {
        public void open() {}
        public void openFrontDoor() {}
        public void openBackDoor() {}
    }
    

    If you compile this program, the compiler produces a warning because open was deprecated (in the interface). What can you do to get rid of that warning?

    Answer: You can deprecate the implementation of open:

    public class MyHouse implements House { 
        // The documentation is 
        // inherited from the interface.
        @Deprecated
        public void open() {} 
        public void openFrontDoor() {}
        public void openBackDoor() {}
    }
    

    Alternatively, you can suppress the warning:

    public class MyHouse implements House { 
        @SuppressWarnings("deprecation")
        public void open() {} 
        public void openFrontDoor() {}
        public void openBackDoor() {}
    }
    
  3. Will the following code compile without error? Why or why not?

    public @interface Meal { ... }
    
    @Meal("breakfast", mainDish="cereal")
    @Meal("lunch", mainDish="pizza")
    @Meal("dinner", mainDish="salad")
    public void evaluateDiet() { ... }
    

    Answer: The code fails to compile. Before JDK 8, repeatable annotations are not supported. As of JDK 8, the code fails to compile because the Meal annotation type was not defined to be repeatable. It can be fixed by adding the @Repeatable meta-annotation and defining a container annotation type:

    public class AnnotationTest {
    
        public @interface MealContainer {
            Meal[] value();
        }
    
        @java.lang.annotation.Repeatable(MealContainer.class)
        public @interface Meal {
            String value();
            String mainDish();
        }
    
        @Meal(value="breakfast", mainDish="cereal")
        @Meal(value="lunch", mainDish="pizza")
        @Meal(value="dinner", mainDish="salad")
        public void evaluateDiet() { }
    }
    

Exercises

  1. Exercise: Define an annotation type for an enhancement request with elements idsynopsisengineer, and date. Specify the default value as unassigned for engineer and unknown for date.

    Answer:

    /**
     * Describes the Request-for-Enhancement (RFE) annotation type.
     */
    public @interface RequestForEnhancement {
        int id();
        String synopsis();
        String engineer() default "[unassigned]";
        String date() default "[unknown]";
    }

 

Type Annotations and Pluggable Type Systems

Before the Java SE 8 release, annotations could only be applied to declarations. As of the Java SE 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you use a type. A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses. This form of annotation is called a type annotation and several examples are provided in Annotations Basics.

Type annotations were created to support improved analysis of Java programs way of ensuring stronger type checking. The Java SE 8 release does not provide a type checking framework, but it allows you to write (or download) a type checking framework that is implemented as one or more pluggable modules that are used in conjunction with the Java compiler.

For example, you want to ensure that a particular variable in your program is never assigned to null; you want to avoid triggering a NullPointerException. You can write a custom plug-in to check for this. You would then modify your code to annotate that particular variable, indicating that it is never assigned to null. The variable declaration might look like this:

@NonNull String str;

When you compile the code, including the NonNull module at the command line, the compiler prints a warning if it detects a potential problem, allowing you to modify the code to avoid the error. After you correct the code to remove all warnings, this particular error will not occur when the program runs.

You can use multiple type-checking modules where each module checks for a different kind of error. In this way, you can build on top of the Java type system, adding specific checks when and where you want them.

With the judicious use of type annotations and the presence of pluggable type checkers, you can write code that is stronger and less prone to error.

In many cases, you do not have to write your own type checking modules. There are third parties who have done the work for you. For example, you might want to take advantage of the Checker Framework created by the University of Washington. This framework includes a NonNull module, as well as a regular expression module, and a mutex lock module. For more information, see the Checker Framework.

 

 

 

 

 

posted @   papering  阅读(77)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2020-12-22 gRPC Motivation and Design Principles | gRPC https://grpc.io/blog/principles/
2019-12-22 linux中高并发socket最大连接数的优化详解
2019-12-22 socket数
2017-12-22 数据教训 有计划地且按时按量地产生(更新)数据
2017-12-22 sql 语法树 常量
2017-12-22 定时任务 bash 对远程数据库 备份 读写
2017-12-22 监控脚本更新数据结果 要求当前小时更新的数据 所分布的产生时间
点击右上角即可分享
微信分享提示