最近我的Eclipse在關於Annotation的問題上老是莫名其妙的出些問題, 最常見的就是關於Annotation中的@Override這個標記了。
按照定義@Override在java中表示覆寫一個基類中的方法,其在源碼中的定義如下
/**
* Indicates that a method declaration is intended to override a
* method declaration in a superclass. If a method is annotated with
* this annotation type but does not override a superclass method,
* compilers are required to generate an error message.
*
也就是說在基類中聲明的method在繼承類中實現的話久可以用@Override進行標註。但是問題時如果我的method時定義在一個interface中間而不是abstract class時這個標註會不會報錯了?
我開始在機器中裝的是jdk1.6,進行開發的時候定義介面如下:
public interface AttachmentManager {
public void saveAttachment(Attachment attachment);
public void saveAttachment(AttachmentVO attachmentVO, String collegeId);
public Attachment getAttachment(String id);
public void deleteAttachment(String id);
}
然後實現這個介面:
public class AttachmentManagerImpl implements AttachmentManager {
private AttachmentDao attachmentDao;
public void saveAttachment(Attachment attachment) {
attachmentDao.saveAttachment(attachment);
}
@Override
public void setAttachmentDao(AttachmentDao attachmentDao) {
this.attachmentDao = attachmentDao;
}
@Override
public void saveAttachment(AttachmentVO attachmentVO, String collegeId) {
MultipartFile data = attachmentVO.getData();
Attachment attachment = new Attachment();
try {
attachment = AttachmentUtil.createAttachment(data,collegeId);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
attachmentDao.saveAttachment(attachment);
}
@Override
public Attachment getAttachment(String id) {
Attachment attachment = attachmentDao.getAttachment(id);
return attachment;
}
@Override
public void deleteAttachment(String id) {
Attachment attachment = getAttachment(id);
AttachmentUtil.deleteAttachment(attachment);
attachmentDao.deleteAttachment(attachment);
}
可以正常編譯和運行,但是前幾天Eclipse出了點小問題,然後就無法運行,提示的是無法找到method,當我把@Override刪除以後一切正常,加上後又是一樣。然後我把jdk卸載裝了1.5,問題依舊,我又在命令列下進行編譯還是一樣,於是我將1.6重新裝回,將Eclipse重新安裝,運行成功,不再報錯。
我上網查了查這個問題,大致的原因和我所碰到的情況一致,@override注釋在jdk1.5環境下只能用於對繼承的類的方法的重寫,而不能用於對實現的介面中的方法的實現。
但是我之前裝的1.6版本為什麼會出現這個問題我只能認為是我的eclipse的原因了,只有天知道。