How to get a JavaDoc of a method at run time?

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();
    }
  }
}

Leave a Comment