最近我的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的原因了,只有天知道。