Java基础巩固系列 注解(Annotation)

本文介绍了Java中注解的基本概念及使用方法,包括JDK提供的常用注解如@Override、@Deprecated和@SuppressWarnings,同时还展示了如何自定义注解并使用元注解进行修饰。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述:

基本的Annotation

 

自定义Annotation:

 

提取Annotation信息:

 

元注解:

 

元注解@Retention的相关介绍:

 

元注解@Target的相关介绍:

 

TestAnnotation 代码示例:

/**
 * 注解
 * 1.JDK提供的常用的注解
 * @Override: 限定重写父类方法, 该注释只能用于方法
 * @Deprecated: 用于表示某个程序元素(类, 方法等)已过时
 * @SuppressWarnings: 抑制编译器警告
 * 2.如何定义一个注解
 * 3.元注解
 */
public class TestAnnotation {
    public static void main(String[] args) {
        Person p = new Student();
        p.walk();
        p.eat();

        @SuppressWarnings("unused")
        List list = new ArrayList();


        @SuppressWarnings("unused")
        int i =10;
//        System.out.println(i);
    }
}

@MyAnnotation(value = "Peter")
class Student extends Person {

    @Override
    public void walk() {
        System.out.println("学生走路");
    }

    @Override
    public void eat() {
        System.out.println("学生吃饭");
    }
}

@Deprecated
class Person {
    String name;
    int age;

    public Person() {

    }

    @MyAnnotation(value = "Peter")
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @MyAnnotation(value = "Peter")
    public void walk() {
        System.out.println("走路");
    }

    @Deprecated
    public void eat() {
        System.out.println("吃饭");
    }
}

结果:

学生走路
学生吃饭

 

MyAnnotation 代码示例:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;

//自定义注解
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default  "hello";
}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值