Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional class import/ load

In a Groovy script is it possible to do a conditional import statement?

if (test){
    import this.package.class
} else {
    import that.package.class
}

The background to this is wanting to use something on MacOS 10.5 which only has JDK1.5 so one specific class is unavailable, but I have found someone who has written a back-port for it.

like image 839
john renfrew Avatar asked Aug 05 '26 09:08

john renfrew


1 Answers

There is no way to conditionally import a class, but you can achieve something similar by attempting to load the class and then load another class if that one is not found.

Here's just an example:

def someClass
try {
    someClass = "org.apache.webdavlib.WebdavFile" as Class
} catch (Exception ex) {
    someClass = "java.io.File" as Class
}

def someInstance = someClass.newInstance("~/project/temp.log")

assert "java.io.File" == someInstance.getClass().getName()
like image 63
John Wagenleitner Avatar answered Aug 08 '26 04:08

John Wagenleitner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!