search
HomeJavajavaTutorialHow to use Java annotation Annotaton

1. Three basic Annotaton

@Override: To limit a method, it is to override the parent class method. This annotation can only be used for methods
@Deprecated: Used to represent a certain program Elements (classes, methods, etc.) are obsolete
@SuppressWarnings: Suppress compiler warnings

@Override

class father{
   public void fly(){}
}
class son extends father{
    @Override
    public void fly() {
        super.fly();
    }
}

Interpretation

@Override means that son overrides the fly method

Details

If there is no @Override, the fly method will still be rewritten

class father{
   public void fly(){}
}
class son extends father{
    public void fly() {
        super.fly();
    }
}

If the @Override annotation is written, the compiler will check whether the method overrides the parent class method , if rewritten, the compilation will pass. If it is not rewritten, a compilation error occurs.

How to use Java annotation Annotaton

@Override can only modify methods, not other classes, packages, properties, etc.

//@Override底层代码
@Target(ElementType.METHOD)//ElementType.METHOD说明@Override只能修饰方法
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

@Deprecated

public class Deprecatedtext {
    public static void main(String[] args) {
        father father1 = new father();
        father1.fly();
    }
}
@Deprecated
class father{
    @Deprecated
   public void fly(){}
}

Interpretation

@Deprecated means that a certain program element (class, method, etc.) is obsolete, and will be reminded by a horizontal line in the middle of the word. Indicates that use is not recommended.

Effect

How to use Java annotation Annotaton

Details can modify methods, classes, packages, parameters, etc.

//@Deprecated底层代码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})//说明Deprecated能修饰方法,类,包,参数等等
public @interface Deprecated {
}

2.@Deprecated can play the role Make the compatibility transition between old and new versions

@SuppressWarnings

@SuppressWarnings("all")
class father{
   public void fly(){}
}

Interpretation

@SuppressWarnings annotation can be used to suppress warning information{""}Write the warning information you want to suppress

Effect

How to use Java annotation Annotaton

How to use Java annotation Annotaton

Details

1. The scope of @SuppressWarnings is related to the location where you place it

public class Enumtext {
    @SuppressWarnings("all")//作用范围在main方法
    public static void main(String[] args) {
        father father1 = new father();
        father1.fly();
    }
}
@SuppressWarnings("all")//作用范围在father类
class father{
   public void fly(){}
}

The specified warning type is

all, suppress all warnings
boxing, suppress warnings related to packaging/disassembly operations
cast, suppress warnings related to forced transformation operations
dep-ann, suppress warnings related to elimination comments
deprecation, suppress warnings related to elimination
fallthrough, suppress warnings related to omission of break in switch statements
finally, suppress and not returned Warnings related to finally blocks
hiding, suppressing warnings related to local variables that hide variables
incomplete-switch, suppressing warnings related to missing items in switch statements (enum case)
javadoc, suppressing warnings related to javadoc related warnings
nls, suppress warnings related to non-nls string literals
null, suppress warnings related to null value analysis
rawtypes, suppress warnings related to the use of raw types
resource, Suppress warnings related to the use of resources of type Closeable
restriction, suppress warnings related to the use of deprecated or forbidden references
serial, suppress warnings related to the omission of the serialVersionUID field in serializable classes
static- access, suppress warnings related to incorrect static access
static-method, suppress warnings related to methods that may be declared static
super, suppress warnings related to replacement methods that do not contain super calls
synthetic-access, suppresses warnings related to unoptimized access to internal classes
sync-override, suppresses warnings related to missed synchronization due to overriding synchronization methods
unchecked, suppresses warnings related to unchecked operations
unqualified-field-access, suppress warnings related to unqualified field access
unused, suppress warnings related to unused code and disabled code

How to use Java annotation Annotaton

Meta-annotation

  • Retention specifies the scope of the annotation, three types of SOURCE, CLASS, RUNTIME

  • Target specifies the annotation. Where to use

  • Documented to specify whether the annotation will be reflected in javadoc

  • Inherited The subclass will inherit the parent class annotation

Retention

  • RetentionPolicy.SOURCE: After the compiler uses it, discard the comment directly

  • RetentionPolicy.CLASS: Compiler Record the annotations in the class file, and the JVM will not retain the annotations when running java

  • RetentionPolicy.PUNTIME: The compiler records the annotations in the class file, and the JVM will retain the annotations when running java

Retention case

@Override the bottom layer (the shortcut key for IDEA to enter the bottom layer is Ctrl B)

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)//表示@Override在编译器使用后,直接丢弃注释
public @interface Override {
}

Target

The value of Target
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
//   1.CONSTRUCTOR:用于描述构造器
    2.FIELD:用于描述域
    3.LOCAL_VARIABLE:用于描述局部变量
    4.METHOD:用于描述方法
    5.PACKAGE:用于描述包
    6.PARAMETER:用于描述参数
    7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
Target case

@Deprecated underlying

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})//表示@Documented在这些地方可以写注解
public @interface Deprecated {
}

Documented

Documented case

@Deprecated bottom layer

@Documented//@Deprecated代码会被保存到生产的文档中
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}

Inherited

The Annotation modified by it will have inheritance. If a class uses an Annotation modified by @Inherited, its subclasses will automatically have this annotation

The above is the detailed content of How to use Java annotation Annotaton. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment