知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

      • Theory:Functional decomposition
      • Theory:Paradigms
      • Theory:Overloading
      • Theory:Write, compile, and run
      • Theory:Annotations basics
        • Annotation, where are you?
        • Built-in annotations
        • Annotation elements
        • @Deprecated annotation
        • Wow, a custom annotation
        • Conclusion
      • Theory:JVM, JRE, and JDK
      • Theory:Jave Archive
      • Theory:Running programs on your computer
      • Theory:Enums in Java
      • Theory:Fields and methods in enum
      • Theory:StringBuilder
      • Theory:Immutability
      • Theory:Boxing and unboxing
      • Theory:Introduction to generic programming
      • Theory:Generics and Object
      • Theory:What are collections
      • Theory:The collections Framework overview
      • Theory:ArrayList
      • Theory:The List interface
      • Theory:Comparable
      • Theory:Processing strings
      • Theory:Initialization blocks
      • Theory:Introduction to API
      • Theory:Generic methods
    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 应知
Jim
2022-06-21
目录

Theory:Annotations basics

An annotation is a special Java instrument that provides information about a program. Its main goal is to make programmers' lives easier. To give them a more formal definition, annotations are a form of metadata, which means they are not part of the program itself.

You can mark classes, methods, fields, variables, and other parts of a program with annotations. When you do it, annotations provide information for the compiler, for some development tools, or for frameworks and libraries at runtime.

Now that you know how useful they are, you have no other choice but to make friends with annotations!

# Annotation, where are you?

But do you understand that the day has come and what is in front of you is your first annotation? All annotations are started with the @ symbol followed by the annotation name, and they are usually marked with a color different from the code.

Here is an example:

@Override
public void printName() {
    System.out.println(this.name);
}
1
2
3
4

@Override is an annotation here.

提示

You can also mark a class/method/field/etc with two or more annotations!

# Built-in annotations

Java has several built-in annotations. If you want to use other annotations, you will need to include libraries or frameworks, or even create your own annotations.

But first, let's discuss the three main built-in annotations that were presented to the world in Java 5:

  • @Deprecated
    
    1

    is a simple annotation which means that the marked method (or class, field, and so on) is deprecated, that is, obsolete and should no longer be used. This annotation causes a compile warning if the code is used.

    @Deprecated
    public void oldMethod() {
        System.out.println("Hello!");
    }
    
    1
    2
    3
    4
  • @SuppressWarnings
    
    1

    commands the compiler to disable some compile-time warnings. You specify in parameters which warnings you don't want to see, for example:

    @SuppressWarnings("unused")
    public void printHello() {
        System.out.println("Hello!");
    }
    
    1
    2
    3
    4

Imagine you created a method printHello but didn't use it. The compiler doesn't like unused methods, but with the @SuppressWarnings("unused") annotation where "unused" is a parameter, you can disable that compile warning. This annotation can be applied to classes, methods, fields, local variables, and other parts of the program.

  • @Override marks a method that overrides a superclass method. This annotation can only be applied to methods. We will consider it in detail in a separate topic about overriding methods.

# Annotation elements

Some annotations have elements, where an element is similar to an attribute or a parameter. You have already seen an example of an element in a previous section. Let's give it a closer look.

Remember the annotation called @SuppressWarnings? It takes the type of warning you want to disable as a parameter.

@SuppressWarnings("unused") 
public void printHello() {
    System.out.println("Hello!");
}
1
2
3
4

If you show some curiosity and look inside the @SuppressWarnings annotation, you will find out that it has only one element named value. Because the element is just one and is called value, it can be omitted, but the full definition will look like this:

@SuppressWarnings(value = "unused")
public void printHello() {
    System.out.println("Hello!");
}
1
2
3
4

提示

Pay attention the full definition could be omitted for value field only. For other field names full definition is required

An annotation element can also be an array. In fact, the actual type of value in@SuppressWarnings annotation is String[]:

@SuppressWarnings({"unused", "deprecation"})
public void printHello() { ... }
1
2

"deprecation", as you might have guessed from the name, instructs the compiler to suppress warnings about the use of deprecated code.

Finally, the last thing you need to know is that some annotations have a default value for an element, and some don't.

@SuppressWarnings // wrong syntax, there is no default value!
public void printHello() {
    System.out.println("Hello!");
}
1
2
3
4

For example, @SuppressWarnings doesn't have a default value, so you can't skip it.

# @Deprecated annotation

For many years the @Deprecated annotation didn't have any elements, but starting from Java 9 it has two: since and forRemoval. We will quickly break them down because there is a big chance you will meet them in practice.

  • since requires the version (String) in which the annotated element has become deprecated. The default value is an empty string.
  • forRemoval indicates whether the annotated element is to be removed in a future version. The default value is false.
@Deprecated(since = "5.3", forRemoval = true)
public void printHello() {
    System.out.println("Hello!");
}
1
2
3
4

The example above means that the printHello method has been deprecated since version 5.3 of our library and it will be removed in the next release.

# Wow, a custom annotation

Fear not: we won't create any new annotations in this topic. But we will look into two annotations from external sources. Both @NotNull and @Range annotations mark classes, fields, methods, and parameters.

The @NotNull annotation indicates that:

  • a variable cannot be null;
  • a method should not return null.

And the @Range annotation indicates that:

  • a variable always belongs to the specified range;
  • a method returns an integer number that belongs to the specified range.

Now let's look at our class called GameCharacter:

class GameCharacter {

    @NotNull
    private String login;

    @Range(min = 1, max = 100)
    private int level = 1;

    public GameCharacter(
            @NotNull String login,
            @Range(min = 1, max = 100) int level) {

        this.login = login;
        this.level = level;
    }

    @NotNull
    public String getLogin() {
        return login;
    }

    @Range(min = 1, max = 100)
    public int getLevel() {
        return level;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Here these annotations will help you by showing warnings if login contains null, or if the level of your character is less than 1 or more than 100.

@NotNull is taken from JetBrains (opens new window) and @Range is taken from the popular framework Hibernate.

# Conclusion

In this topic, you finally learned about annotations and now you know that their main goal is to provide some important information to the compiler, development tools, frameworks, and libraries at runtime. Some annotations contain elements, for which you can provide values. You also learned about the three built-in annotations and looked at a couple of examples of custom annotations. And in the next topic, you will learn how to create them yourself.

In real-life programming, you will meet plenty of different annotations, but there is no reason to be afraid: they are here to make your life easier and you can always find the explanations you need in documentation.

编辑 (opens new window)
#Java
上次更新: 2022/09/26, 16:55:15
Theory:Write, compile, and run
Theory:JVM, JRE, and JDK

← Theory:Write, compile, and run Theory:JVM, JRE, and JDK→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式