Today I am studying the first lesson of annotation (basic)
The main content learned today:
1.注解是什么
2.自定义注解的简单声明
3.JDK提供了的注解有哪些
annotation:
注解为我们在代码中添加信息提供了一种形式化的方法,
让我们可以在稍后的某个时间点可以非常便捷的使用这
些数据或者是帮助我们提供必要的控制、约束、信息等
等注解和泛型一样已经被广泛使用,注解首次出现是在
JDK5.0之后。
----------------《java编程语言高级特性》咕嘟咖啡杨海滨老师
使用注解,可以在编译时就进行检查,格式检查。好比
我们之前重写方法在方法上一行加一个@Override,而且
注解提供了很好的对代码跟踪的依赖性。
Self-built annotation:
声明:@interface + 你想要的注解名。
使用:与别的JDK提供的注解使用方法相似。
Annotations provided in the JDK:
1.@Override(重写):
用来表示一个方法是否被重写,并且验证重写的这个方法是否符合重写的语法。
2.@Deprecated(不宜用,弃用):
用来告诉开发者它标注的某个元素由于风险高不宜使用或者弃用了.
一般情况下,我们会在那些在不同环境中使用起来可能不一样的方法属性和类使用Depreacted注解。
3.@SuppressWarnings(抑制编译器警告):
用它可以取消编译器对某个方法、属性、类的警告。
4.@FunctionalInterface(功能接口):
表示声明了函数式接口,JDK8中首次出现。
OverriedTest class (used to test @Override annotation):
package LessonForAnnotation01;
class Game
{
//也可以标注在这,推荐标注在这
@Deprecated
public void setGameName(String name, String release_date)
{
System.out.println("public void setGameName(String name, String release_date)");
}
}
class GamePlayer extends Game
{
//重写Game里的setGameName方法
//注解可以多重标注
//可以标注在这@Deprecated
@Override
public void setGameName(String name, String release_date)
{
System.out.println("Override Successful");
}
}
public class OverrideTest
{
public static void main(String[] args)
{
}
}
DeprecatedTest class (used to test @Deprected annotation):
package LessonForAnnotation01;
@Deprecated
class Game02
{
}
public class DeprecatedTest
{
@Deprecated
public String test;
public DeprecatedTest(String test)
{
this.test = test;
}
public String getTest()
{
return this.test;
}
@Deprecated
public void setTestFunction()
{
System.out.println("public void setTestFunction()");
}
public static void main(String[] args)
{
DeprecatedTest dt1 = new DeprecatedTest("芜湖");
dt1.setTestFunction();
System.out.println(dt1.getTest());
}
}
SuppressWarningTest class (used to test @SuppressWarning annotation):
package LessonForAnnotation01;
//@SuppressWarnings("all")代表下面全部警告忽略
@SuppressWarnings(value = {
"all" })
public class SuppressWarningTest
{
public static void main(String[] args)
{
int a = 0;
int b = 0;
}
}
FunctionalInterfaceTestable interface (used to test @FunctionalInterface annotation):
package LessonForAnnotation01;
//注解此接口为函数式接口
@FunctionalInterface
public interface FunctionalInterfaceTestable
{
public void getGame();
// public void getGame02();
}
GameError annotation (simple self-built annotation):
package LessonForAnnotation01;
public @interface GameError
{
//运用的范围和JDK自带的一致
}
At last:
部分文字来源于:
咕嘟咖啡杨海滨老师 — 《java编程语言高级特性》
在这里十分感谢老师能够给我带来学习的激情。
2020.10.11
can reprint my study diary but please indicate the source, thank you.
complete