Java MessageFormat Null Values
Asked Answered
C

3

9

What is the best way to treat null values in Java MessageFormat

MessageFormat.format("Value: {0}",null);

=> Value: null

but actually a "Value: " would be nice.

Same with date

MessageFormat.format("Value: {0,date,medium}",null);

=> Value: null

a "Value: " whould be much more appreciated.

Is there any way to do this? I tried choice

{0,choice,null#|notnull#{0,date,dd.MM.yyyy – HH:mm:ss}}

which results in invalid choice format, what is correct to check for "null" or "not null"?

Catercousin answered 8/7, 2014 at 22:59 Comment(0)
H
5

MessageFormat is only null-tolerant; that is, it will handle a null argument. If you want to have a default value appear instead of something if the value you're working with is null, you have two options:

You can either do a ternary...

MessageFormat.format("Value: {0}", null == value ? "" : value));

...or use StringUtils.defaultIfBlank() from commons-lang instead:

MessageFormat.format("Value: {0}", StringUtils.defaultIfBlank(value, ""));
Haddock answered 8/7, 2014 at 23:57 Comment(1)
What if I need to work with a date? something like: MessageFormat.format("Value: {0,date,dd/MM/yyyy}", aDate); ?Campanulate
R
-1

Yes, you cant. Look at javadoc. Unfortunately, it dind't work with NULL.

Try use optional

    Optional.ofNullable(value).orElse(0)

Or see example how to use ChoiceFormat and MessageFormat.



    For more sophisticated patterns, you can use a ChoiceFormat to produce correct forms for singular and plural:

     MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
     double[] filelimits = {0,1,2};
     String[] filepart = {"no files","one file","{0,number} files"};
     ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
     form.setFormatByArgumentIndex(0, fileform);

     int fileCount = 1273;
     String diskName = "MyDisk";
     Object[] testArgs = {new Long(fileCount), diskName};

     System.out.println(form.format(testArgs));

    The output with different values for fileCount:
     The disk "MyDisk" contains no files.
     The disk "MyDisk" contains one file.
     The disk "MyDisk" contains 1,273 files.

    You can create the ChoiceFormat programmatically, as in the above example, or by using a pattern. See ChoiceFormat for more information.


     form.applyPattern(
        "There {0,choice,0#are no files|1#is one file|1
Refuel answered 30/1, 2015 at 11:29 Comment(1)
This has no use, because custom format for null value will not apply (Check method MessageFormat.subformat)Olmos
O
-1

I need that now in my generator class by a mask.

Reason: User can save mask with multiple types say "{0} {1,number,000} {2,date,MMyyyy}. And user have data where can be nulls. For result i use MessageFormat class. And want empty string without default 'null' text. Null check is not that easy, because it will means replace pattern that is used for many records (not just one). And default empty value don't exists for number or date.

So if someone still needs solution. I give my.

Add this methods/classes (I have all in one class)

private static Object[] replaceNulls2NullValues( Object[] values ) {
    for ( int i = 0; i < values.length; i++ )
        if ( values[i] == null )
            values[i] = NullFormatValue.NULL_FORMAT_VALUE;
    return values;
}

private static MessageFormat modifyFormaterFormats( MessageFormat formater ) {
    formater.setFormats( Arrays.stream( formater.getFormats() ).map( ( f ) -> ( f != null ) ? new NullHandlingFormatWrapper( f ) : null ).toArray( ( l ) -> new Format[l] ) );
    return formater;
}

private static final class NullFormatValue {

    static final Object NULL_FORMAT_VALUE = new NullFormatValue();

    private NullFormatValue() {
    }

    @Override
    public String toString() {
        return "";
    }
}

private static class NullHandlingFormatWrapper extends Format {

    protected Format wrappedFormat;

    public NullHandlingFormatWrapper( Format format ) {
        wrappedFormat = format;
    }

    @Override
    public StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition pos ) {
        if ( !( obj instanceof NullFormatValue ) )
            wrappedFormat.format( obj, toAppendTo, pos );

        return toAppendTo;
    }

    @Override
    public Object parseObject( String source, ParsePosition pos ) {
        return wrappedFormat.parseObject( source, pos );
    }
}

and for result call

modifyFormaterFormats( new MessageFormat( pattern ) ).format( replaceNulls2NullValues( parameters ) );
Olmos answered 2/2, 2018 at 13:0 Comment(1)
Wow. I'm really not sure I agree with this code. You go to great lengths to introduce a null object pattern when this is absolutely unnecessary. A simple null check or something that provides a default value is really all you require. Worse, you don't explain why this solution is preferable to any of the other answers available.Haddock

© 2022 - 2024 — McMap. All rights reserved.