35

Its easy to get a method Name of a Class at run time
BUT
How i can get a JavaDoc of a method at run time ?

As the following example

Our Class that include JavaDoc of our target method

public class MyClass {
    /**
     * 
     * @param x value of ....
     * @return result of ....
     */
    public String myMethod(int x) {
        return "any value";
    }

}

Our Class that has a main method

public class TestJava {
    public static void main(String[] args) {
        // get Class method Name at run time
        String methodName = MyClass.class.getMethods()[0].getName();
        System.out.println(methodName); // will print myMethod
        // How to  get a JavaDoc of myMethod `method` at run time
        // MyClass.class.getMethods()[0].????
        // expected to print a JavaDoc of myMethod
    }
}
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
  • 1
    What do you mean, "at run time"? The short answer is that you don't. – Dave Newton Mar 09 '13 at 15:14
  • For what purpose? The user running the program almost certainly isn't a programmer: what good is showing him the Javadoc going to do? – user207421 Mar 11 '13 at 00:25
  • 2
    This is actually a new [feature](http://sergiodelamo.es/preview-of-groovy-3/) for groovy 3. I could see this becoming a new way to provide documentation for rest api's. For instance using swagger. – John Mercier Jun 30 '17 at 11:17

5 Answers5

25

The only way to get it at runtime is to use custom annotations.

Create a custom annotation class:

@Retention(RUNTIME)
@Target(value = METHOD)
public @interface ServiceDef {
  /**
   * This provides description when generating docs.
   */
  public String desc() default "";
  /**
   * This provides params when generating docs.
   */
  public String[] params();
}

Use it on a method of a class, e.g.:

@ServiceDef(desc = "This is an utility class",
            params = {"name - the name","format - the format"})     
public void read(String name, String format)

Inspect the annotations via reflection:

for (Method method : Sample.class.getMethods()) {
  if (Modifier.isPublic(method.getModifiers())) {
    ServiceDef serviceDef = method.getAnnotation(ServiceDef.class);
    if (serviceDef != null) {
      String[] params = serviceDef.params();
      String descOfMethod = serviceDef.desc();
    }
  }
}
dimo414
  • 47,227
  • 18
  • 148
  • 244
Liam
  • 2,837
  • 23
  • 36
17

Annotation processors have access to the Javadoc comments in the source code. If you have control over the compilation process for the classes whose Javadoc you are interested in, you can use an annotation processor to grab the Javadoc at compile-time and make it available later at runtime.

This is the approach used in the therapi-runtime-javadoc project (disclosure: which I authored and am shamelessly plugging).

dnault
  • 8,340
  • 1
  • 34
  • 53
  • An interesting approach. Now a bit later do you have experiences from production? – Thorbjørn Ravn Andersen Mar 26 '18 at 11:07
  • 3
    @ThorbjørnRavnAndersen It has been working fine in the [therapi-json-rpc](https://github.com/dnault/therapi-json-rpc) project. As for lessons learned, version 0.4.0 stores the Javadoc in JSON class path resources instead of generated Java classes. This produces smaller JARs and is kinder to the class loader. The annotation processor and runtime library are now separate artifacts for more flexibility. This is one of my passion projects, and I try to respond to [issues](https://github.com/dnault/therapi-runtime-javadoc/issues) quickly. – dnault Mar 27 '18 at 19:40
  • 1
    Hi @dnault, is it also possible to access javadoc warnings and errors using that approach? Fx a Link to another class, but with a spelling error. IDEs will highlight stuff like that but I haven't found a way to access it by AbstractProcessor and visitors/scanners. I am using this guide/example: https://alvinalexander.com/java/jwarehouse/openjdk-8/langtools/test/tools/javac/diags/DocCommentProcessor.java.shtml – Hervian May 29 '20 at 17:55
  • @Hervian I don't think it would help you with that. If you do discover a portable way to access the imports so that you can validate links, I'd love to hear about it :-) – dnault May 29 '20 at 21:00
14

You can't : the class file doesn't contain the comments.

A "solution" would be to generate the javadoc as HTML when you build your program and to build an URL from the name of the class and the name of the method. You could also generate the javadoc in a more suitable format than HTML using the doclet API.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

You can run javadoc programmatically and passing options to generate documentation for the class that you want and then parsing the generated document to get the documentation for the method that you want. You will need the source code at runtime because comments are not in the class file.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
3

Comments do not have a representation in bytecode, they get stripped out by the compiler and aren't available "at runtime".

cara
  • 1,012
  • 1
  • 9
  • 15