`

java1.5中{@inheritDoc}的使用

    博客分类:
  • Java
 
阅读更多

java1.5中@Override还不能用在interface上,只能用在class上。给我们的代码注释带来了一定的烦恼。 
为了表明一个方法是实现一个interface,我们可以使用{@inheritDoc}来标识,同时,该tag会把super type的注释复制下来。 

Java代码  收藏代码
  1. public interface A {  
  2.     /** 
  3.      * F method. 
  4.      * @param a para a. 
  5.      * @param b para b.    
  6.      * @return f(a,b).   
  7.      * */  
  8.     public int f(int a, int b);  
  9. }  
  10. class B implements A {  
  11.     /**  
  12.      * {@inheritDoc} 
  13.      * */  
  14.     public int f(int a, int b) {  
  15.         return 0;  
  16.     }  
  17. }  

在生成的html中,我们可以看到B的方法注释完全复制自A. 
Java代码  收藏代码
  1. public int f(int a,int b)  
  2.   
  3. F method.   
  4.   
  5. Specified by:  
  6. f in interface A  
  7. Parameters:  
  8. a - para a.  
  9. b - para b.   
  10. Returns:  
  11. f(a,b).  


当然,我们有可能改变接口的约定(不推荐这么做),这时,可以只注释改变的注释元素。 
Java代码  收藏代码
  1. /**  
  2.  * {@inheritDoc} 
  3.  * F method, compute sum.  
  4.  * @param a a>=0 
  5.  * @return a+b 
  6.  * */  
  7. public int f(int a, int b) {  
  8.     return 0;  
  9. }  

这个的javadoc的结果为 
Java代码  收藏代码
  1. f  
  2. public int f(int a,int b)  
  3.   
  4. F method. F method, compute sum.   
  5.   
  6. Specified by:  
  7. f in interface A  
  8. Parameters:  
  9. a - a>=0  
  10. b - para b.   
  11. Returns:  
  12. a+b  

可以看到,方法的主体注释文本为两个主体注释的拼接,参数,返回值都可以覆盖掉接口的注释。 

对于异常的注释的继承比较特殊: 
若子类没有声明父类的异常,则父类的异常注释不会被继承。 
子类只会继承它和父类共同声明的异常。 
当然,异常的注释,子类可以覆盖掉父类的注释。 

推荐的异常注释是子类列出所有的异常,如果父类也声明了该异常,则用 
@throws IOException {@inheritDoc} 
继承该异常的注释。 

所有的注释继承都有拼接功能,如 
* @return {@inheritDoc} a+b. 
* @throws IOException {@inheritDoc} when file is missed. 
返回值注释会继承父类的返回值注释,在加上新的注释。 
异常注释会继承父类的异常注释,在加上新的注释。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics