java - 找不到 : java. time.LocalDateTime(java.lang.String) 的匹配构造函数

标签 java grails grails-orm grails-domain-class java-time

我有一个 Grails 3.1.2 应用程序

我的域类之一是 Goal

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

class Goal {
    String name
    String description
    LocalDateTime targetDate
    Date dateCreated
    Date lastUpdated
    static constraints = {
        name(nullable: false, blank: false)
    }
}

当我在 Goal 实例上调用 validate 时,我得到:

  • 字段“targetDate”上的对象“com.liftyourgame.model.Goal”中出现字段错误:值被拒绝 [2016-01-28T15:10:39.000Z];代码 [com.liftyourgame.model.Goal.targetDate.typeMismatch.error,com.liftyourgame.model.Goal.targetDate.typeMismatch,goal.targetDate.typeMismatch.error,goal.targetDate.typeMismatch,typeMismatch.com.liftyourgame.model。 Goal.targetDate,typeMismatch.targetDate,typeMismatch.java.time.LocalDateTime,typeMismatch];参数 [目标日期];默认消息[找不到匹配的构造函数:java.time.LocalDateTime(java.lang.String)]

如何更改验证以便不需要此构造函数?

最佳答案

How can I change the validation so it doesn't need this constructor?

你不能,但验证并不是真正的问题。数据绑定(bind)器就是问题所在。默认 Binder 尚未内置对 LocalDateTime 的支持。

您可以像这样注册自己的转换器:

转换器:

// src/main/groovy/demo/MyDateTimeConverter.groovy
package demo

import grails.databinding.converters.ValueConverter

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

class MyDateTimeConverter implements ValueConverter {
    @Override
    boolean canConvert(Object value) {
        value instanceof String
    }

    @Override
    Object convert(Object value) {
        def fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
        LocalDateTime.parse(value, fmt)
    }

    @Override
    Class<?> getTargetType() {
        LocalDateTime
    }
}

将其注册为 Bean:

// grails-app/conf/spring/resources.groovy
beans = {
    myConverter demo.MyDateTimeConverter
}

关于java - 找不到 : java. time.LocalDateTime(java.lang.String) 的匹配构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785999/

相关文章:

java - 序列化时如何保存静态变量

json - grails rest客户将字符串转换为java.util.Date

unit-testing - 在 grails 中重写域属性的 setter 是否正确?

java - 源代码编译前的JOOQ代码生成

java - JedisPool 无法连接到 telnet redis 服务器

java - 在Grails中,是否有一种方法可以限制HTTP请求方法类型(allowedMethods映射除外)?

jquery - Geb测试:缺少表单元素

spring - grails 3 约束异常

hibernate - 未触发级联更新

java - 基于值的 XmlUnit 顺序