gaurav
gaurav

Reputation: 51

How to get java class in groovy using reflection

I have a groovy script, from which I want to access a static method of java class. The name of java class and method, will be input to groovy. I will read the name of class and method, and invoke like this:

"$apiClass"."$apiMethod"("UTC")

I am new to groovy, and not sure how to use refelction efficiently. Below is the code :

    def exp="[MyDateUtil:getFirstDate](UTC)"

    def m=exp=~ /(?<=\[).+?(?=\])/

    assert m instanceof Matcher

    def apiDef

    while(m.find()) {

          apiDef =m.group()

    }

    def (apiClass, apiMethod) = apiDef.split(":")

    def output = "$apiClass"."$apiMethod"("UTC")`

I was thinking below line will work, but its not able to get the class

def output = "$apiClass"."$apiMethod"("UTC")

If I give only method name as variable, it works fine:

def output = MyDateUtil."$apiMethod"("UTC")

Upvotes: 0

Views: 866

Answers (1)

npskirk
npskirk

Reputation: 1188

You need to use fully qualified class names, and also be sure that the class loader has loaded the class, meaning you've referred to the class in some other context that caused it to be loaded.


// groovysh session

groovy:000> dateClass = Class.forName("java.util.Date")
===> class java.util.Date

groovy:000> x=dateClass.invokeMethod("newInstance", null)
===> Tue Jul 16 08:12:51 PDT 2019

groovy:000> x
===> Tue Jul 16 08:12:51 PDT 2019

// or

groovy:000> dateClass."newInstance"()
===> Tue Jul 16 08:24:02 PDT 2019

// or

groovy:000> dateClass."newInstance"(8456245)
===> Wed Dec 31 18:20:56 PST 1969

// also

groovy:000> ni="newInstance"
===> newInstance

groovy:000> dateClass."${ni}"()
===> Tue Jul 16 08:27:45 PDT 2019

groovy:000> dateClass."${ni}"(8456245)
===> Wed Dec 31 18:20:56 PST 1969

Upvotes: 1

Related Questions