Java的注解-预置注解

2019-07-29  本文已影响0人  一块自由的砖

预置的注解

Java 语言本身已经提供了一些现成的注解。

@Deprecated

用来标记过时的元素。编译器在编译阶段遇到这个注解时会发出提醒警告,告诉开发者正在调用一个过时的元素比如过时的方法、过时的类、过时的成员变量。

public class Demo {
    //注解过时
    @Deprecated
    public void say(){
        System.out.println("Noting has to say!");
    }
    
    public void speak(){
        System.out.println("I have a dream!");
    }
}

定义了一个 Demo 类,它有两个方法 say() 和 speak() ,其中 say() 被 @Deprecated 注解。

@Override

子类要重写父类中被 @Override 修饰的方法

@SuppressWarnings

阻止警告的意思。之前说过调用被 @Deprecated 注解的方法后,编译器会警告提醒,而有时候开发者会忽略这种警告,他们可以在调用的地方通过 @SuppressWarnings 达到目的。

@SuppressWarnings("deprecation")
public void test(){
    Demo demo = new Demo();
    demo.say();
    demo.speak();
}

@FunctionalInterface

函数式接口注解,这个是 Java 1.8 版本引入的新特性。函数式编程很火,所以 Java 8 也及时添加了这个特性。函数式接口 (Functional Interface) 就是一个具有一个方法的普通接口。

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

在进行线程开发中常用的 Runnable 就是一个典型的函数式接口,源码可以看到被 @FunctionalInterface 注解。

上一篇 下一篇

猜你喜欢

热点阅读