Java Reference
In-Depth Information
Listing 13-6. Implementing a Custom Formatter Using the Formattable Interface
// FormattablePerson.java
package com.jdojo.format;
import java.util.Formattable;
import java.util.Formatter;
import java.util.FormattableFlags;
public 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 our result is stored in it and the caller will get it
formatter.format(str);
}
}
Your Formattable person has a first name and a last name. You have kept the logic inside the formatTo() method
simple. You check for alternate flag '#' . If this flag is used in the format specifier, you format the person name in
the "LastName, FirstName" format. If the alternate flag is not used, you format the person name in the "FirstName
LastName" format. You also support uppercase variant 'S' of 's' conversion. If 'S' conversion is used, you format the
person name in uppercase. Your logic does not use other values of the flags, width, and precision. The flags are passed
in as an int value as bitmask. To check if a flag was passed, you will need to use the bitwise & operator. The operand to
be used in the bitwise & operator are defined by constants in the java.util.FormattableFlags class. For example, to
check if the format specifier uses a left-justify '-' flag, you will need to use the following logic:
int leftJustifiedFlagValue = FormattableFlags.LEFT_JUSTIFY & flags;
if (leftJustifiedFlagValue == FormattableFlags.LEFT_JUSTIFY) {
// Left-justified flag '-' is used
}
Search WWH ::




Custom Search