java BeanUtils 复制属性:注册 ConvertUtils
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12719645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BeanUtils Copy Properties: Registering ConvertUtils
提问by JR Galia
I have web application written in Java. Im using BeanUtils.copyProperties
method. If a date
field is null, it throws an error. I solved it by using ConvertUtils.register
method.
我有用 Java 编写的 Web 应用程序。我使用BeanUtils.copyProperties
方法。如果date
字段为空,则会引发错误。我是用ConvertUtils.register
方法解决的。
ConvertUtils.register(new DateConverter(null), Date.class);
It works now, but what is the correct way of using ConvertUtils.register
. Where should it be placed?
它现在可以工作,但是使用ConvertUtils.register
. 应该放在哪里?
回答by Yogendra Singh
What you have done is CORRECTfor only one class(Date) type. This is achieved for all the supported types including Date by calling register method on ConvertUtilsBean
as below:
您所做的仅对一种类(日期)类型是正确的。这是通过调用 register 方法对包括 Date 在内的所有支持的类型实现的,ConvertUtilsBean
如下所示:
ConvertUtilsBean convertUtilsBean = BeanUtilsBean.getInstance().getConvertUtils();
convertUtilsBean.register(false, true, -1);
Here, first argument false
means don't throw conversion exception. Second argument true
represents, if there is exception, use null as default value. Third argument -1
represent that array types will be defaulted to null. If you want to default arrays with specific size, mention the size as third parameter.
这里,第一个参数false
表示不抛出转换异常。第二个参数true
表示,如果有异常,则使用 null 作为默认值。第三个参数-1
表示数组类型将默认为 null。如果要使用特定大小的默认数组,请将大小作为第三个参数提及。
Refer more details here (ConvertUtilsBean Javadoc).
请参阅此处的更多详细信息(ConvertUtilsBean Javadoc)。
回答by Lluis Martinez
A good place is the ServletContextListener, you just need to do it once.
一个好地方是 ServletContextListener,你只需要做一次。
回答by JohnyB
in order to register your converters in proper place check below links:
为了在适当的位置注册您的转换器,请检查以下链接:
http://www.coderanch.com/t/459630/Struts/Apache-Commons-Custom-Converter-Implementationhttp://mail-archives.apache.org/mod_mbox/struts-user/200303.mbox/%[email protected]%3E
http://www.coderanch.com/t/459630/Struts/Apache-Commons-Custom-Converter-Implementation http://mail-archives.apache.org/mod_mbox/struts-user/200303.mbox/%3COE27foV1qdiixjnzi9500001205d hotmail.com%3E