无法在groovy闭包中的newInstance中找到从此列表中调用的方法< init>() [英] Could not find which method <init>() to invoke from this list on newInstance in groovy closure

查看:855
本文介绍了无法在groovy闭包中的newInstance中找到从此列表中调用的方法< init>()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习groovy,我正在尝试使用所有字段的默认值动态初始化我的类。所以我正在进行的是,我正在获取所有属性的列表并获取该对象的类型并创建该类型的对象,但是在执行 newInstance

I am learning groovy and I am trying to initialize my class dynamically with default values for all fields. So how I am proceeding is, I am taking the list of all the properties and getting the type of that object and create an object of the type, but I am getting error when executing newInstance:

Exception in thread "main" org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
  public java.lang.Boolean#<init>(boolean)
  public java.lang.Boolean#<init>(java.lang.String)
    at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3160)
    at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3097)
    at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1707)
    at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1526)

以下是代码

public static void init() {
        Position position1 = new Position();

        JXPathContext context = JXPathContext.newContext(position1)
        context.createPathAndSetValue('id', '2')

        position1.properties.each { Map.Entry entry ->
            String propertyName = entry.key;
            if (!propertyName.equalsIgnoreCase('class')) {
                Class clazz = position1.class.getDeclaredField(propertyName)?.type
                println "$clazz"
                Object ob = clazz.newInstance()
            }

        }
        Identifier sourceSystemPositionId = new Identifier()

        context.setValue('sourceSystemPositionId/content', 'default-content')
        context.setValue('sourceSystemPositionId/domain', 'default-domain')

        println "$position1"
    }


推荐答案

查看 java docs for java.lang.Boolean 。正如您在构造函数摘要部分中所看到的,此类没有no-arg构造函数(这是异常消息所示)。您必须:

View the java docs for java.lang.Boolean. As you can see in the section Constructor Summary there's no no-arg constructor (and this is what exception message says) for this class. You must either:


  • 使用 boolean 或<$ c调用它(构造函数) $ c> String 参数

  • 使用布尔值的默认值 - false

  • 使用 Boolean.FALSE 初始化值.Brill.TRUE

  • invoke it (constructor) with boolean or String argument
  • use default value for boolean - which is false
  • initialize the value with Boolean.FALSE or Boolean.TRUE

这篇关于无法在groovy闭包中的newInstance中找到从此列表中调用的方法&lt; init&gt;()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆