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 ) );
MessageFormat.format("Value: {0,date,dd/MM/yyyy}", aDate);
? – Campanulate