【问题标题】:Could not find matching constructor for: DomainObjectName(java.lang.String)找不到匹配的构造函数:DomainObjectName(java.lang.String)
【发布时间】:2016-01-26 04:34:09
【问题描述】:

我正在使用命令对象,并且我在命令对象中使用了域对象,如下所示。

class JobCommand {
  List<Country> countries
  String name
  String age
  .....
}

国家域名如下:

@EqualsAndHashCode(includes="id")
class Country{
String id
String name
Date createDate
......
}

我正在从我的 JobController 访问这个 jobCommand 对象,并在我的 gsp 页面中设置我的 Country 字段中的值。 我的 gsp 页面中有一个名为 Country 的搜索字段,其中包含美国、印度、伊朗等国家/地区的选项。

 <g:select name="countries" id="country" 
        from="${Country.findAll()}"
        value="${jobCommand ?.countries}"
        multiple="true" 
        optionKey="id"
        optionValue="name"
 />

当我选择多个国家并单击搜索按钮时,我收到异常“找不到匹配的构造函数:package.Country(java.lang.String)”。

【问题讨论】:

  • 为什么 g:select 标签命名为 country 而命令对象属性命名为 countries
  • 您好罗莎,感谢您的评论。其实你是对的。这是我的打字错误。 g:select 标签名称仅为“国家”。我已经更正了这个问题。
  • 显然缺少构造函数。但是哪一行代码抛出了异常?
  • 数据显示在我的视图中,并且控制台中没有错误日志。所以,我不能说哪行代码引发了异常。我相信它应该是 Country 构造函数,因为消息显示(Could not find matching constructor for: package.Country(java.lang.String)) 。在我看来,只有我能在这里看到上面提到的消息。我们需要在 grails 中明确提及构造函数吗?
  • 异常不在构造函数中,因为该构造函数不存在。异常来自尝试调用构造函数的代码。不仅要查看控制台,还要查看视图中呈现的异常。该堆栈跟踪包含重要信息。在 Grails 中,当您更改默认 id 时,可能会发生意想不到的事情;就像你在Country 中用String 替换它一样。

标签: grails


【解决方案1】:

有两种方法可以将参数绑定到命令对象。 1.使用bindData(http://docs.grails.org/3.1.1/ref/Controllers/bindData.html) 2. 编写我们自己的转换器。我有同样的问题,我自己写了转换器。

编写自己的转换器的步骤: 使用以下方法创建转换器类:

boolean canConvert(value) {
        value instanceof String
    }

    def convert(value) {
        //your logic
    }

    Class<?> getTargetType() {
        //your type
    }

在 bean 内的 resources.groovy 中注册您的转换器{}

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2016-06-17
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多