Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom conversion specifiers in java

Tags:

java

format

I want my data structures to be custom formatted. e.g. I have a DS

Address {
    string house_number,
    string street,
    string city,
    long pin_code,
}

Now, I want to associate certain conversion specifiers with each of these fields.

e.g. house_number -> H
     street -> S,
     city -> C,
     pin_code -> P
     ...

So that something like

myPrintWriter.printf("Mr A lives in %C", address_instance) 

yields "Mr A lives in boston" (if address_instance.city = boston) etc..

It seems there is no easy way to do this. java.util.Formatter seems to be final. The only customization it provides is via the interface Formattable, but that helps in customizing the 's' conversion specifier only. Is there a way to add our custom conversion specifiers? Any help will be much appreciated.

Thanks,

like image 866
baskin Avatar asked Oct 26 '22 01:10

baskin


1 Answers

It seems there is no easy way to do this. java.util.Formatter seems to be final.

That's true, but you can still use composition. I would do something like the following:

class ExtendedFormatter {
    private Formatter defaultFormatter;

    // provide the same methods like the normal Formatter and pipe them through
    // ...

    // then provide your custom method, or hijack one of the existing ones
    // to extend it with the functionality you want
    // ...
    public Formatter format(String format, Object... args) {
         // extract format specifiers from string
         // loop through and get value from param array

         ExtendedFormattable eft = (ExtendedFormattable)args1;
         String specifierResult = eft.toFormat(formatSpecifier);  // %C would return city

         // use specifierResult for the just queried formatSpecifier in your result string
    }
}

The hard part is to know how to attach the different format specifiers to the fields you want to output. The first way I can think of, is to provide your own ExtendedFormattable interface that each class that should be used with the ExtendedFormatter can implement, and return the according values for your custom format specifiers. That could be:

class Address implements ExtendedFormattable {
    public String toFormat(String formatSpecifier) { // just an very simple signature example
         // your custom return values here ...  
    }
}

There's also annotations, but I think that's not a very viable way.

A sample call would look like:

ExtendedFormatter ef = new ExtendedFormatter();
ef.format("Mr A lives in %C", address_instance);
like image 158
MicSim Avatar answered Nov 09 '22 07:11

MicSim