参考答案
1. @Deprecated注解的作用
- 注解@Deprecated可以标记Java API状态,表示API已过时和不被推荐使用。
- 如果使用或执行代码重写,会被编译器发出警告,或被IDE的语法检查做黄色的警告。
2. @Deprecated注解的使用场景
之前存在的类,由于以下原因,现在不再继续使用了,但又不确定后期是否会重新使用,就先用@Deprecated注释着,后期依据新的业务/系统需求进行调整。
- 存在某些风险可能导致错误;
- 有更好和更高效的方案;
- 在以后的版本中可能对其无法兼容地进行更改;
- 在以后的版本中可能将其删除。
3. @Deprecated注解的示范代码
使用 @Deprecated 注解示例代码:
class Person {
private int id;
private String name;
@Deprecated(since="1.1")
Person(){}
Person(int id, String name) {
this.id = id;
this.name = name;
}
@Deprecated(since="1.1")
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
@Deprecated(since="1.1")
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
public class DeprecatedTest {
public static void main(String[] args) {
Person p1 = new Person();
p1.setId(1);
p1.setName("Sam");
Person p2 = new Person(2, "Bob");
}
}
编译器发出警告:

验证下,是调用标记了@Deprecated注解的API的部分:

感兴趣的童鞋可以测试下~
以上,是Java面试题【@Deprecated注解的作用】的参考答案。
输出,是最好的学习方法。
欢迎在评论区留下你的问题、笔记或知识点补充~
—end—
