Java中的注解

2022-01-14  本文已影响0人  GoLearning轻松学
注解

注解是JDK1.5引入的新特性,大部分框架都用注解简化代码并提高编码效率。
常见的有:
@Override 重写 标识覆盖它的父类的方法
@Deprecated 已过期 标识方法是不建议使用的
@SuppressWarnings 告知编译器忽略指定的警告
Annotation通常在package、Class、Field、Method上,目的是与其他类、成员变量、方法区分开来,或者说做一个标识。

注解的定义:通过@interface关键字进行定义
public @interface AnnotationClass
{
    
}

它的形式跟接口很类似,不过前面多出了一个@的符号。

元注解

元注解只能用在注解上面
@Target 所用到的注解的作用域在哪里
@Retention:标识注解传递存活的时间
@Document 将注解中的元素包含到Javadoc中
@Inherited 允许子类继承父类中的注解

定义注解

@Target(ElementType.TYPE) //表示AnnotationClass注解可以用于什么地方,可用于给一个类型进行注解,比如类、接口、枚举
@Retention(RetentionPolicy.RUNTIME)//表示AnnotationClass注解传递存活时间,注解可保留到程序运行时被加载到JVM中
public @interface AnnotationClass
{
    //Integer heightx();//不能使用封装类型
    int height();//参数的类型只能是基本类型
    String shape();
    int deep();
    int width() default 10;

}

使用注解

//多个属性之间要用逗号隔开,赋值方式在括号内以value = ""的方式。
@AnnotationClass(height = 11,shape = "ddd",deep = 45)
public class Plants {
    private int height;
    private String shape;
    private int deep;
    private int width;

    public Plants(int height, String shape, int deep, int width) {
        this.height = height;
        this.shape = shape;
        this.deep = deep;
        this.width = width;
    }

    public Plants() {
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getShape() {
        return shape;
    }

    public void setShape(String shape) {
        this.shape = shape;
    }

    public int getDeep() {
        return deep;
    }

    public void setDeep(int deep) {
        this.deep = deep;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    @Override
    public String toString() {
        return "Plants{" +
                "height=" + height +
                ", shape='" + shape + '\'' +
                ", deep=" + deep +
                ", width=" + width +
                '}';
    }
}

上一篇 下一篇

猜你喜欢

热点阅读