First of all, you cannot directly get comments using reflection, and you cannot get them by using a library that reads the ".class" file. The information is not present the ".class" file, and reflection only knows about information is directly available from there.
As people have pointed out, you can only get comments if you have the source code. And if you have a source code file you should be able to extract comments using JavaParser
or (possibly) some other library, ... or by writing your own parser.
The problem will be mapping from a Class
object to the corresponding source code file. Let us assume that you have multiple source trees corresponding to multiple JARs on the application's classpath. You will need:
- the URIs for each JAR or directory on the classpath,
- a mapping from each URI to a corresponding source tree.
The approach would be:
- Get the fully qualified class name from the
Class
object.
- Map the classname to a relative Java source path; e.g.
foo.bar.Baz
would become foo/bar/Baz.java
- Use
clazz.getProtectionDomain().getCodeSource().getLocation().toURI()
to get the URI from whence the class was loaded.
- Map the URI to the corresponding source tree ... using your mappings.
- Resolve the relative path relative to the root of the source tree.
- Open the source file.
Some of the above steps could present problems. For example:
- in step 2, you need to deal with nested classes,
- in step 3,
getCodeSource()
could return null
,
- in step 3, the resulting
URI
could have a weird protocol,
- if your mapping are incomplete, step 4 could fail,
- if your source code doesn't match the code you are executing, step 5 could fail.
Once you have the source file open, you construct a Reader
and parse the source code ... using your chosen Java parser.
If yours was a "green field" project, it may be simpler to define a custom annotation type (with retention runtime) and turn your comments into annotations. These annotations can be extracted simply and quickly, with none of the possible failure modes in the above.
But the flipside is that annotations are cumbersome to write (in the source code) compared to comments. Also, you would be bloating the ".class" files with the extra annotations.
I haven't got how to do it as all the [JavaParser] examples just parse given string.
The javadoc shows that you can use a JavaParser
instance to parse a File
, an InputStream
, a Reader
or a String
.