註解不一定是你想要的。標記接口是一種將類型屬性工作到類型本身的方法。例如,如果你正要開始編寫代碼看起來像這樣:
@interface ContainableTag{}
@ContainableTag public class Foo {}
// ... elsewhere...
/**
* Adds obj as a child element.
* @throws IllegalArgumentException if obj is not tagged with
* the ContainableTag annotation.
*/
public void addElement(Object obj){
if (!obj.getClass().isAnnotationPresent(ContainableTag.class))
throw new IllegalArgumentException("obj is not a ContainableTag");
// add the containable tag as an element
}
然後考慮,如果你真的不認爲這看起來更好:
interface ContainableTag {}
public class Foo implements ContainableTag {}
// ... elsewhere...
public void addElement(ContainableTag ct){
// add the containable tag as an element
}
當然,標籤化的界面不提供關於類型本身提供什麼行爲的任何信息,但它允許其他類型強制執行此非行爲屬性確實。如果ObjectOutputStream
有writeObject(Serializable)
方法,而不是writeObject(Object)
,我當然會免受許多煩人的錯誤。
編輯:我有not insignificant support在這裏。
您應該在SO上指出關於此主題的現有查詢。他們還包含很多參考資料。不過,你挖出的有趣的文章。 – ShiDoiSi 2009-09-17 07:30:12