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

前端 未结 5 1955
无人及你
无人及你 2020-11-29 11:51

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 f

相关标签:
5条回答
  • 2020-11-29 12:33

    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.

    0 讨论(0)
  • 2020-11-29 12:35

    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();
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-29 12:45

    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).

    0 讨论(0)
  • 2020-11-29 12:45

    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.

    0 讨论(0)
  • 2020-11-29 12:49

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

    0 讨论(0)
提交回复
热议问题