在控制器中
@RequestMapping(value = "/testCalendar")
public String testCalendar(Calendar time){
System.out.println(time == null);
return "request ok" ;
}
并在浏览器中打开以下URL:127.0.0.1:8090 / test / testCalendar
它收到以下错误消息
springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.Calendar]: Is it an abstract class?; nested exception is java.lang.InstantiationException] with root cause
java.lang.InstantiationException: null
atsun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
如果我想要日历为空,该怎么办?
我尝试
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Calendar.class, new CalendarEditor());
binder.registerCustomEditor(Date.class, new DateEditor());
}
但仍然不能正常工作,请帮助我。
答案 0 :(得分:0)
protected
我怀疑问题是Calendar
是protected
类。因此,您无法从不相关的类实例化。参见this other Answer。
一种替代方法是使用常规的后备类GregorianCalendar
。
更好的解决方案是完全避免使用Calendar
和GregorianCalendar
。这些是经过精心设计的类,具有很多缺陷。几年前,它们被通过 java.time 类实现的JSR 310取代。
ZonedDateTime
GregorianCalendar
的替代项是ZonedDateTime
。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
请注意, java.time 类故意缺少公共构造函数。因此,这也意味着缺少无参数构造函数。相反,他们使用工厂方法,例如上面看到的ZonedDateTime.now
。作为指导,请研究java.time naming conventions。
如果您的框架需要无参数构造函数,则需要找到解决方法或解决方法。
java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和SimpleDateFormat
。
目前位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310。
您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*
类。
在哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如Interval
,YearWeek
,YearQuarter
和more。