import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ExploreDocumentation {
private static final List<String> CASES = new ArrayList<String>();
private static String q(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
}
sb.append("\"");
return sb.toString();
}
private static void addCase(String name, String summary, String expectedJson, String actualJson, boolean passed) {
CASES.add("{\"name\":" + q(name) + ",\"summary\":" + q(summary)
+ ",\"expected\":" + expectedJson + ",\"actual\":" + actualJson + ",\"passed\":" + passed + "}");
}
private static File findJavadocBin() {
File javaHome = new File(System.getProperty("java.home"));
File[] candidates = new File[]{
new File(javaHome, "bin/javadoc.exe"),
new File(javaHome.getParentFile(), "bin/javadoc.exe"),
new File(javaHome, "bin/javadoc"),
new File(javaHome.getParentFile(), "bin/javadoc")
};
for (File f : candidates) {
if (f.exists() && f.isFile()) {
return f;
}
}
throw new IllegalStateException("javadoc binary not found under " + javaHome);
}
private static void deleteTree(Path dir) {
if (dir == null || !Files.exists(dir)) return;
try {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException {
Files.deleteIfExists(d);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException ignored) {
}
}
private static class ProcOut {
final int code;
final String combined;
ProcOut(int code, String combined) {
this.code = code;
this.combined = combined;
}
}
private static ProcOut runCommand(List<String> cmd) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process proc = pb.start();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8));
try {
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
br.close();
}
int code = proc.waitFor();
return new ProcOut(code, sb.toString());
}
private static double square(double num) {
return num * num;
}
public static void main(String[] args) throws Exception {
File javadocBin = findJavadocBin();
// Case 1: Run real local javadoc.exe on a clean documented Java source file
Path tmp1 = Files.createTempDirectory("mbsky-javadoc-clean-");
try {
Path src = tmp1.resolve("SquareCalc.java");
Path docOut = tmp1.resolve("docs");
String sourceCode = ""
+ "import java.io.IOException;\n"
+ "import java.io.Serializable;\n"
+ "/**\n"
+ " * 演示标准 Javadoc 文档注释与常用块级、行内标签。\n"
+ " * 参考常量值为 {@value #DEFAULT_SCALE},可配合 {@link #square(double)} 使用。\n"
+ " * @author MBSky Lab\n"
+ " * @version 1.2\n"
+ " * @since 1.0\n"
+ " */\n"
+ "public class SquareCalc implements Serializable {\n"
+ " private static final long serialVersionUID = 1L;\n"
+ " /** 默认比例因子,文档根目录示例 {@docRoot}。 */\n"
+ " public static final int DEFAULT_SCALE = 100;\n"
+ " /** @serial 记录最近一次计算结果 */\n"
+ " private double lastResult;\n"
+ " /**\n"
+ " * 计算输入数值的平方,链接样式示例 {@linkplain Math Math 类}。\n"
+ " * @param num 待求平方的双精度数值\n"
+ " * @return num 的平方结果\n"
+ " * @see Math#pow(double, double)\n"
+ " */\n"
+ " public double square(double num) {\n"
+ " lastResult = num * num;\n"
+ " return lastResult;\n"
+ " }\n"
+ " /**\n"
+ " * 解析文本为双精度数值。\n"
+ " * @param text 数字字符串\n"
+ " * @return 解析后的数值\n"
+ " * @throws IOException 当输入为空时抛出\n"
+ " */\n"
+ " public double parseNumber(String text) throws IOException {\n"
+ " if (text == null) throw new IOException(\"empty\");\n"
+ " return Double.parseDouble(text);\n"
+ " }\n"
+ " /**\n"
+ " * 旧版辅助入口。\n"
+ " * @deprecated 请改用 {@link #square(double)}\n"
+ " * @param n 输入值\n"
+ " * @return 平方值\n"
+ " */\n"
+ " @Deprecated\n"
+ " public double legacySquare(double n) { return square(n); }\n"
+ "}\n";
Files.write(src, sourceCode.getBytes(StandardCharsets.UTF_8));
ProcOut po = runCommand(Arrays.asList(
javadocBin.getAbsolutePath(),
"-encoding", "UTF-8",
"-charset", "UTF-8",
"-author", "-version",
"-d", docOut.toAbsolutePath().toString(),
src.toAbsolutePath().toString()
));
boolean hasIndex = Files.exists(docOut.resolve("index.html"));
boolean hasClassDoc = Files.exists(docOut.resolve("SquareCalc.html"));
boolean hasConstValues = Files.exists(docOut.resolve("constant-values.html"));
boolean hasDeprecatedList = Files.exists(docOut.resolve("deprecated-list.html"));
String classHtml = hasClassDoc
? new String(Files.readAllBytes(docOut.resolve("SquareCalc.html")), StandardCharsets.UTF_8)
: "";
boolean containsKeyTags = classHtml.contains("MBSky Lab")
&& classHtml.contains("1.2")
&& classHtml.contains("100")
&& classHtml.contains("IOException");
String exp1 = "{\"exit_code\":0,\"has_index\":true,\"has_class_html\":true,\"has_const_and_deprecated\":true,\"html_contains_tags\":true}";
String act1 = "{\"exit_code\":" + po.code
+ ",\"has_index\":" + hasIndex
+ ",\"has_class_html\":" + hasClassDoc
+ ",\"has_const_and_deprecated\":" + (hasConstValues && hasDeprecatedList)
+ ",\"html_contains_tags\":" + containsKeyTags + "}";
addCase(
"javadoc_generate_html_real",
"调用本地 JDK 8 javadoc.exe 生成完整 HTML 文档并校验 index.html、类页面与标签输出",
exp1, act1, exp1.equals(act1)
);
} finally {
deleteTree(tmp1);
}
// Case 2: Demonstrate JDK 8 doclint rejecting @return on a void method (like source SquareNum.main)
Path tmp2 = Files.createTempDirectory("mbsky-javadoc-void-");
try {
Path src2 = tmp2.resolve("VoidReturnDemo.java");
Path outStrict = tmp2.resolve("strict");
Path outRelaxed = tmp2.resolve("relaxed");
String badSource = ""
+ "public class VoidReturnDemo {\n"
+ " /**\n"
+ " * 演示在 void 方法上误用 @return 标签触发 doclint 告警/错误。\n"
+ " * @param args 命令行参数\n"
+ " * @return Nothing.\n"
+ " */\n"
+ " public static void main(String[] args) {}\n"
+ "}\n";
Files.write(src2, badSource.getBytes(StandardCharsets.UTF_8));
ProcOut strictRes = runCommand(Arrays.asList(
javadocBin.getAbsolutePath(),
"-encoding", "UTF-8",
"-d", outStrict.toAbsolutePath().toString(),
src2.toAbsolutePath().toString()
));
ProcOut relaxedRes = runCommand(Arrays.asList(
javadocBin.getAbsolutePath(),
"-Xdoclint:none",
"-encoding", "UTF-8",
"-d", outRelaxed.toAbsolutePath().toString(),
src2.toAbsolutePath().toString()
));
boolean strictFailedOnVoid = strictRes.code != 0 && strictRes.combined.toLowerCase().contains("void");
boolean relaxedSucceededWithWarning = relaxedRes.code == 0 && relaxedRes.combined.toLowerCase().contains("void");
String exp2 = "{\"strict_doclint_rejected_void_return\":true,\"doclint_none_generated_with_warning\":true}";
String act2 = "{\"strict_doclint_rejected_void_return\":" + strictFailedOnVoid
+ ",\"doclint_none_generated_with_warning\":" + relaxedSucceededWithWarning + "}";
addCase(
"javadoc_void_return_warning",
"实测 JDK 8 doclint 拦截 void 方法上的 @return 标签及 -Xdoclint:none 退化为告警的行为",
exp2, act2, exp2.equals(act2)
);
} finally {
deleteTree(tmp2);
}
// Case 3: Verify square() calculation & Double.parseDouble()
double sqPos = square(3.5);
double sqNeg = square(-4.0);
double parsed = Double.parseDouble("12.5");
String exp3 = "{\"sq_3_5\":12.25,\"sq_neg_4\":16.0,\"parsed\":12.5}";
String act3 = "{\"sq_3_5\":" + sqPos + ",\"sq_neg_4\":" + sqNeg + ",\"parsed\":" + parsed + "}";
addCase(
"square_calc_runtime_behavior",
"验证 SquareNum 示例核心平方运算与 Double.parseDouble 解析",
exp3, act3, exp3.equals(act3)
);
// Case 4: Verify Javadoc 17-tag taxonomy (12 block tags + 5 inline tags)
List<String> blockTags = Arrays.asList(
"@author", "@deprecated", "@exception", "@param", "@return", "@see",
"@serial", "@serialData", "@serialField", "@since", "@throws", "@version"
);
List<String> inlineTags = Arrays.asList(
"{@docRoot}", "{@inheritDoc}", "{@link}", "{@linkplain}", "{@value}"
);
String exp4 = "{\"block_tags\":12,\"inline_tags\":5,\"total\":17}";
String act4 = "{\"block_tags\":" + blockTags.size()
+ ",\"inline_tags\":" + inlineTags.size()
+ ",\"total\":" + (blockTags.size() + inlineTags.size()) + "}";
addCase(
"javadoc_tag_inventory",
"核对 17 项标准 Javadoc 标签分类(12 项块级标签与 5 项花括号行内标签)",
exp4, act4, exp4.equals(act4)
);
StringBuilder out = new StringBuilder();
out.append("{\"version\":").append(q("OpenJDK " + System.getProperty("java.version"))).append(",\"cases\":[");
for (int i = 0; i < CASES.size(); i++) {
if (i > 0) out.append(",");
out.append(CASES.get(i));
}
out.append("]}");
System.out.println(out.toString());
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/java-documentation-lab/ExploreDocumentation.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreDocumentation.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1113.zip
课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip