Annotation Type FormatMethod


  • @Documented
    @Retention(CLASS)
    @Target({METHOD,CONSTRUCTOR})
    public @interface FormatMethod
    Annotation for a method that takes a printf-style format string as an argument followed by arguments for that format string.

    This annotation is used in conjunction with FormatString to denote a method that takes a printf-style format string and its format arguments. In any method annotated as FormatMethod without a FormatString parameter, the first String parameter is assumed to be the format string. For example, the following two methods are equivalent:

     @FormatMethod void log(Locale l, @FormatString String logMessage, Object... args) {}
     @FormatMethod void log(Locale l, String logMessage, Object... args) {}
     

    Using FormatMethod on a method header will ensure the following for the parameters passed to the method:

    1. A format string is either:
      • A compile time constant value (see CompileTimeConstant for more info).

        The following example is valid:

         public class Foo {
           static final String staticFinalLogMessage = "foo";
           @FormatMethod void log(@FormatString String format, Object... args) {}
           void validLogs() {
             log("String literal");
             log(staticFinalLogMessage);
           }
         }

        However the following would be invalid:

         public class Foo{
           @FormatMethod void log(@FormatString String format, Object... args) {}
           void invalidLog(String notCompileTimeConstant) {
             log(notCompileTimeConstant);
           }
         }
      • An effectively final variable that was assigned to a compile time constant value. This is to permit the following common case:
         String format = "Some long format string: %s";
         log(format, arg);
         
      • Another FormatString annotated parameter. Ex:
         public class Foo {
           static final String staticFinalLogMessage = "foo";
           @FormatMethod void log(@FormatString String format, Object... args) {}
           @FormatMethod void validLog(@FormatString String format, Object... args) {
             log(format, args);
           }
         }
    2. The format string will be valid for the input format arguments. In the case that the actual format string parameter has a compile time constant value, this will compare the actual format string value to the types of the passed in format arguments to ensure validity. In the case that the actual format string parameter is a parameter that was annotated FormatString itself, this will ensure that the types of the arguments passed to the callee match the types of the arguments in the caller.