Element ใดๆ ที่ annotate ด้วย @Deprecated หมายถึง element นั้นไม่ควรใช้แล้ว ด้วยเหตุผล:
- ใช้เสี่ยงต่อ errors
- อาจ incompatible ใน future versions
- อาจถูกลบใน future versions
- มี solution ที่ดีและมีประสิทธิภาพมากกว่าแล้ว
Java 9 เพิ่ม 2 elements ใหม่: attributes since และ forRemoval
1) since
ระบุ version ที่ API element ถูก deprecated
@Deprecated(since = "9")
public void oldMethod() { ... }
2) forRemoval
ระบุว่า API element นี้อาจถูกลบใน version ถัดไป และควร migrate
@Deprecated(forRemoval = true)
public void dangerousMethod() { ... }
รวมทั้งสอง
@Deprecated(since = "9", forRemoval = true)
public void legacyMethod() { ... }
ตัวอย่างจาก Java 9 Documentation
Boolean Class - ใช้ since attribute

ใน Boolean class มีเมธอดที่ deprecated since Java 9
System Class - ใช้ forRemoval attribute

ใน System class มีเมธอดที่ deprecated for removal
การใช้งานกับ Compiler และ Tools
Compiler Warnings
// เปิด deprecation warnings
javac -Xlint:deprecation MyClass.java
// เปิด forRemoval warnings
javac -Xlint:deprecation,forRemoval MyClass.java
jdeprscan Tool
// สแกน deprecated APIs
jdeprscan MyClass.class
// สแกนเฉพาะ forRemoval
jdeprscan --for-removal MyClass.class
// แสดง deprecated APIs ทั้งหมดของ release
jdeprscan --list --release 9
Best Practices สำหรับ Library Authors
- ใช้
@Deprecated(since="x.y", forRemoval=false)สำหรับ APIs ที่ deprecated แต่ยังคงอยู่ - ใช้
@Deprecated(since="x.y", forRemoval=true)สำหรับ APIs ที่วางแผนจะลบ - ระบุ alternative API ใน Javadoc
{@link NewClass#newMethod()} - ให้ migration path ชัดเจนใน documentation
- ทดสอบด้วย
jdeprscan --for-removalก่อน release
ตัวอย่าง Javadoc ที่ดี
/**
* @deprecated Since 9.0, use {@link #newBetterMethod()} instead.
* This method will be removed in a future release.
*/
@Deprecated(since = "9", forRemoval = true)
public void oldMethod() {
// implementation
}
Impact บน Developers
- IDE แสดง warning ดีกว่า (แสดง since version, forRemoval status)
- Build tools (Maven/Gradle) สามารถ fail build สำหรับ forRemoval=true
- jdeprscan ช่วย audit codebase ก่อน upgrade Java
- ช่วยวางแผน migration timeline ได้ชัดเจน