Groovy way to dynamically instantiate a class from String

前端 未结 2 1981
滥情空心
滥情空心 2021-01-01 11:27

The answers of this question about the Groovy way to dynamically invoke a static method were very helpful but I\'m having trouble with the following case:

I defined

相关标签:
2条回答
  • 2021-01-01 11:52

    This works, using the underlying GroovyClassLoader:

    def instance = this.class.classLoader.loadClass( 'Item', true, false )?.newInstance()
    
    0 讨论(0)
  • 2021-01-01 11:55

    I just had to do this and found an interesting way--so I thought I'd come back and mention it.

    I had A problem with this because I wanted to pass a value to newInstance (use a non-default constructor) and all the solutions seemed to be a little bit of work (I'm lazy, okay?)

    Anyway, suppose you want to create a new Integer(5)... try this:

    c = "java.lang.Integer"
    p = "5"
    def result = Eval.me("return new ${c}(${p})")
    assert(result == 5)
    

    Worked really well although I'm sure it's about the slowest solution possible. Has the advantage that the method is applicable to many other situations.

    0 讨论(0)
提交回复
热议问题