Implementing a Custom Formatter Using the Formattable Interface - Java Language Basics

Java examples for Language Basics:Number Format

Description

Implementing a Custom Formatter Using the Formattable Interface

Demo Code

import java.util.Formattable;
import java.util.FormattableFlags;
import java.util.Formatter;

public class Main {
  public static void main(String[] argv) {
    FormattablePerson fp = new FormattablePerson("Ken", "Smith");
    System.out.printf("%s %n", fp);
    System.out.printf("%#s %n", fp);
    System.out.printf("%S %n", fp);
    System.out.printf("%#S %n", fp);
  }//from  www.j a va 2s  .c  om
}

class FormattablePerson implements Formattable {
  private String firstName = "Unknown";
  private String lastName = "Unknown";

  public FormattablePerson(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  // Other code goes here...

  public void formatTo(Formatter formatter, int flags, int width, int precision) {
    String str = this.firstName + " " + this.lastName;

    int alternateFlagValue = FormattableFlags.ALTERNATE & flags;
    if (alternateFlagValue == FormattableFlags.ALTERNATE) {
      str = this.lastName + ", " + this.firstName;
    }

    // Check if uppercase variant of the conversio is being used
    int upperFlagValue = FormattableFlags.UPPERCASE & flags;
    if (upperFlagValue == FormattableFlags.UPPERCASE) {
      str = str.toUpperCase();
    }

    // Call the format() method of formatter argument so that out
    // result is stored in it and the caller will get it
    formatter.format(str);
  }
}

Result


Related Tutorials