哪些地方需要添加注释
首先,我们需要确定一下,添加注释的目的是什么?(手动思考10秒)。
我认为添加注释,是为了程序更容易理解与维护,特别是维护,更是对自己代码负责的一种体现。
那基于这样的目的,在日常开发中,我们需要在哪些地方添加注释呢?
类,接口。
这一部分注释是必须的。在这里,我们需要使用javadoc注释,需要标明,创建者,创建时间,版本,以及该类的作用。如下所示:
package com.andyqian.utils;/*** @author: andy* @date: 18-01-05* @version: 1.0.0* @description: 生成PDF 工具类*/public class PdfUtil {}
方法
在方法中,我们需要对入参,出参,以及返回值,均要标明。如下所示:
/** * 生成pdf文件 * @param htmlContent 待生成pdf的 html内容 * @param file 生成pdf文件地址 * @see PdfUtils#getFontPath() * @return true 生成成功 false 生成失败 */ public static boolean generatePdf(String htmlContent,File file){ … return result; }
常量
对常量,我们需要使用多行注释,进行标明该常量的用途,如下所示:
/*** @author: andy* @date: 18-01-05* @version: 0.0.1* @description:*/public class StatusConsts { /** * 博客地址 */ public static final String BLOG=“#”;}
关键算法上
在关键算法上,添加注释并且按照顺序依次标明,写明白该方法为什么这么做。如下所示:
/** * 应用场景: * 1.在windows下,使用Thread.currentThread()获取路径时,出现空对象,导致不能使用 * 2.在linux下,使用PdfUtils.class获取路径为null, * 获取字体路径 * @return 返回字体路径 */ private static String getFontPath(){ String path=“”; // 1. ClassLoader classLoader= Thread.currentThread()。getContextClassLoader(); URL url = (classLoader==null)?null:classLoader.getResource(“/”); String threadCurrentPath = (url==null)?“”:url.getPath(); // 2. 如果线程获取为null,则使用当前PdfUtils.class加载路径 if(threadCurrentPath==null||“”.equals(threadCurrentPath)){ path = PdfUtils.class.getClass()。getResource(“/”)。getPath(); } // 3.拼接字体路径 StringBuffer stringBuffer = new StringBuffer(path); stringBuffer.append(“/fonts/SIMKAI.TTF”); path = stringBuffer.toString(); return path; }
怎么添加注释?
1. IDEA 自动生成
对于类中的注释,我们可以通过IDEA自动生成。
如IDEA 可以通过:File->Settings->Editor->File and Code Templates->Includes->File Header来设置模板,这样新建文件时,IDEA会按照设置的模板,会自动生成一个注释,就不需要一个一个敲了。
其中标签有:
${USER} : 当前用户。
${DATE} : 当前日期。
${PACKAGE_NAME}:包名。
${TIME}: 当前时间。
${YEAR}: 当前年。
${MONTH}:当前月。
${DAY}: 当前日。
${HOURS}: 当前小时。
${MINUTE}: 当前分钟
注释引用
如果方法中引用了其他的方法,在注释中如何体现呢?细心的朋友,应该已经发现了,在上面的:
/** * 生成pdf文件 * @param htmlContent 待生成pdf的 html内容 * @param file 生成pdf文件地址 * @see PdfUtils#getFontPath() * @return true 生成成功 false 生成失败 */ public static boolean generatePdf(String htmlContent,File file){ … return result; }
中的@see就有这个作用,其语法是:
@see package.class#method label@see #field@see #method(Type, Type,…)@see #method(Type argname, Type argname,…)@see #constructor(Type, Type,…)@see #constructor(Type argname, Type argname,…)
例如:
@see PdfUtils#getFontPath()
如果是同一个类中,package(包名全路径)可以省略。有相同功能的标签有:
{@link package.class#metod}
/** * 生成pdf文件 * @return true 生成成功 false 生成失败 * @throws Exception * {@link PdfUtils#getFontPath()} */ public static boolean generatePdf(String htmlContent,File file){ … }
其区别是:@see必须要在注释行首,{@link}可以在任意位置。
更多烟台培训相关资讯,请扫描下方二维码