Search code examples
javaconstantsjavadoc

char constant display in Javadoc "Constant Field Values" page


Is there a way I can get the generated "Constant Field Values" page to use readable characters instead of integers for char type constants?

For instance, if a class contains the following constants:

public static final char YES = 'Y';
public static final char NO  = 'N';
public static final char ERROR  = 'E';

I want the javadoc constant field values page to have the character representation ('Y', 'N', 'E') not the integer version (69, 78, 89).

We have hundreds of these so I don't want to have to go and add some specific javadoc comment to each occurence (e.g. using @value).


UPDATE: Thanks to SubOptimal's answer below, I managed to use the version 1.6 source code for the ConstantsSummaryWriterImpl that I found here, to modify the writeValue method as follows:

private void writeValue(FieldDoc member) {
    tdAlign("right");
    code();
    if ("char".equals(member.type().toString())) {
        print(Util.escapeHtmlChars("'" + ((char) ((Integer)member.constantValue()).intValue()) + "'"));

    } else {
        print(Util.escapeHtmlChars(member.constantValueExpression()));
    }
    codeEnd();
    tdEnd();
}

Once this class is compiled up and used to override the one in 'tools.jar', the char constants are output as the character, not the number.


Solution

  • You can achieve this by tweaking javadoc itself a little bit.

    1. get the source for javadoc tool (don't worry we need only one file to tweak ;-) )
      I took the file langtools-ce654f4ecfd8.tar.gz from here JDK 7 langtools source
    2. extract the file ConstantsSummaryWriterImpl.java
    3. modify the method getValue(FieldDoc member)

      ...
      private Content getValue(FieldDoc member) {
          Content valueContent;
          if ("char".equals(member.type().toString())) {
              valueContent = new StringContent("'" 
                  + (char) ((Integer) member.constantValue()).intValue()
                  + "'"
              );
          } else {
              valueContent = new StringContent(member.constantValueExpression());
          }
          Content code = HtmlTree.CODE(valueContent);
          return HtmlTree.TD(HtmlStyle.colLast, code);
      }
      ...
      
    4. compile the changed file
      javac -cp ${JAVA_HOME}/lib/tools.jar -d . ConstantsSummaryWriterImpl.java

    5. run the javadoc
      javadoc -J-Xbootclasspath/p:.;${JAVA_HOME}/lib/tools.jar -d api/ Scratch.java

    the file Scratch.java

    public class Scratch {
        public static final char YES = 'Y';
        public static final char NO  = 'N';
        public static final char ERROR  = 'E';
    }