Java MessageFormat空值

Java MessageFormat空值,java,messageformat,Java,Messageformat,在Java MessageFormat中处理空值的最佳方法是什么 MessageFormat.format("Value: {0}",null); => Value: null 但实际上,一个“值:”就好了 日期相同 MessageFormat.format("Value: {0,date,medium}",null); => Value: null 一个“价值观”:你会得到更多的赞赏 有没有办法做到这一点?我试过选择 {0,choice,null#|notnull#{0,d

在Java MessageFormat中处理空值的最佳方法是什么

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

=> Value: null
但实际上,一个“值:”就好了

日期相同

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

=> Value: null
一个“价值观”:你会得到更多的赞赏

有没有办法做到这一点?我试过选择

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

这会导致无效的选择格式,检查“null”或“notnull”的正确方法是什么?

MessageFormat
仅允许null;也就是说,它将处理空参数。如果要在使用的值为null时显示默认值而不是其他值,则有两个选项:

你可以做一个三元

MessageFormat.format("Value: {0}", null == value ? "" : value));
…或改用commons lang:

MessageFormat.format("Value: {0}", StringUtils.defaultIfBlank(value, ""));

是的,你不能。看看javadoc。不幸的是,它不能与NULL一起工作

尝试使用可选的
    Optional.ofNullable(value).orElse(0)
Optional.ofNullable(value).orElse(0)

或者参见如何使用ChoiceFormat和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 对于更复杂的模式,可以使用ChoiceFormat生成单数和复数的正确形式: MessageFormat form=newmessageformat(“磁盘\“{1}\”包含{0}”); double[]filelimits={0,1,2}; 字符串[]filepart={“无文件”,“一个文件”,“{0,编号}文件”}; ChoiceFormat fileform=新的ChoiceFormat(filelimits,filepart); form.setFormatByArgumentIndex(0,fileform); int fileCount=1273; 字符串diskName=“MyDisk”; 对象[]testArgs={new Long(fileCount),diskName}; System.out.println(form.format(testArgs)); 具有不同fileCount值的输出: 磁盘“MyDisk”不包含任何文件。 磁盘“MyDisk”包含一个文件。 “MyDisk”磁盘包含1273个文件。 可以通过编程方式创建ChoiceFormat,如上例所示,也可以使用模式。有关更多信息,请参阅ChoiceFormat。 form.applyPattern(
“有{0,choice,0#没有文件| 1#只有一个文件| 1我现在需要在生成器类中通过掩码使用它

原因: 用户可以使用多种类型保存掩码,例如“{0}{1,number,000}{2,date,MMyyyy}。用户的数据可以为null。对于结果,我使用MessageFormat类。并且希望空字符串没有默认的“null”文本。 空检查并不是那么容易,因为它将意味着替换用于多个记录(而不仅仅是一个)的模式。数字或日期的默认空值不存在

所以,如果有人仍然需要解决方案,我会给出我的答案

添加此方法/类(我在一个类中拥有全部)


如果我需要使用日期怎么办?类似于:
MessageFormat.format(“值:{0,date,dd/MM/yyyy}”,aDate);
?这没有用,因为空值的自定义格式将不适用(检查方法MessageFormat.subformat)哇。我真的不确定我是否同意这段代码。在绝对不必要的情况下,你会不遗余力地引入一个空对象模式。一个简单的空检查或提供默认值的东西就是你真正需要的。更糟糕的是,你没有解释为什么这个解决方案比其他任何可用的答案都更可取。
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 );
    }
}
modifyFormaterFormats( new MessageFormat( pattern ) ).format( replaceNulls2NullValues( parameters ) );