1.什么是JAVA DOC
当我们写完JAVA代码,别人要调用我们的代码的时候要是没有API文档是很痛苦的,只能跟进源码去一个个的看,一个个方法的猜,并且JAVA本来就不是一个重复造轮子的游戏,一般一些常用的轮子早就已经早好了,直接拿来用就是。但是拿来用的时候往往由于API文档的缺失或者不规范,造成使用上的很多痛苦,大家在很多实际工作中经常也会遇到类似的场景:
公司多年累积下来的工具类或者提供底层能力的公共模块里面积累了很多能力,公司为了代码规范也要求我们尽量去调用这些工具类或者公共模块。但是:
没有API文档或者文档写的很烂
参数列表动不动就很长,数十个甚至几十个参数
参数列表没有注释,出现一些莫名其妙的参数,都不知道怎么传
方法名也不能见名知意
造成往往要用这些公共能力的时候甚至还要去读源码
有读源码这个时间,可能自己都重新写了一个了,而且自己写的,可能比祖传下来的那些工具类还更“清爽”一些。于是系统内越来越多工具类堆积,重复造的轮子越来越多,“屎山”越堆越高。
即使有时候我们有API文档,但是各类API文档,格式,内容都不相同,没有统一的规范,读起来其实也很慢。所以有没有一个统一的规范喃?JAVA官方其实早就想到了这个问题,在JDK1.1发布的时候就附带了JAVA DOC,支持用标签注释的方式给各个方法做好规范的说明,然后用JAVA命令一键生成可视化的HTML页面作为API。
2.标签
标签是JAVA DOC的核心,用什么标签,JAVA DOC最后就会对应生成哪些API文档内容:
@author:
/**
* @author John Doe
*/
public class MyClass {
}
@version:
/**
* @version 1.0.1
*/
public class MyClass {
}
@param:
/**
* Concatenates two strings.
* @param string1 The first string to concatenate.
* @param string2 The second string to concatenate.
* @return The concatenated string.
*/
public String concatenateStrings(String string1, String string2) {
return string1 + string2;
}
@return:
/**
* Returns the sum of two integers.
* @param num1 The first integer.
* @param num2 The second integer.
* @return The sum of num1 and num2.
*/
public int add(int num1, int num2) {
return num1 + num2;
}
@throws 或 @exception: 描述方法可能抛出的异常。
/**
* Divides two numbers and throws an exception if the divisor is zero.
* @param dividend The number to be divided.
* @param divisor The divisor.
* @return The result of the division.
* @throws ArithmeticException If the divisor is zero.
*/
public double safeDivide(double dividend, double divisor) {
if (divisor == 0) {
throw new ArithmeticException("Divisor cannot be zero.");
}
return dividend / divisor;
}
@see:
/**
* See {@link java.util.ArrayList} for more information on dynamic arrays.
*/
public class MyDynamicArray {
}
@link: 创建一个链接到其他类、方法或字段的链接。
/**
* This method uses the {@link java.util.Collections#shuffle(List)} method to randomize the list.
*/
public void shuffleList(List<?> list) {
Collections.shuffle(list);
}
@since: 指定该元素是从哪个版本开始引入的。
/**
* A utility class for working with dates.
* @since 1.5
*/
public class DateUtils {
}
@deprecated: 标记不再推荐使用的元素。
/**
* Old method that should not be used anymore.
* @deprecated Use the {@link #newMethod()} instead.
*/
@Deprecated
public void oldMethod() {
}
@inheritDoc: 继承父类或接口的 JavaDoc。
/**
* {@inheritDoc}
*/
@Override
public void someMethod() {
// Implementation
}
@parametricType: 用于描述泛型类型参数。
/**
* Represents a generic collection.
* @param <E> The type of elements in this collection.
*/
public class MyCollection<E> {
}
@serialField 和 @serialData: 用于序列化类的字段和数据。
/**
* A serializable class.
* @serialField name The name of the object.
* @serialData The length of the name.
*/
@Serial
private static final long serialVersionUID = 1L;
private String name;
// serialization logic