开发者

Conditional class import/ load

开发者 https://www.devze.com 2023-03-30 03:58 出处:网络
In a Groovy script is it possible to do a conditional import s开发者_如何学Gotatement? if (test){

In a Groovy script is it possible to do a conditional import s开发者_如何学Gotatement?

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.


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()


Jochen "blackdrag" Theodorou proposed the following on the groovy user list a while ago:

wsh = this.class.classLoader.loadClass("org.codehaus.groovy.scriptom.ActiveXObject").newInstance("WScript.Shell") 

Then you do not need to use the import statement.

Here is the thread on the mailing list


No, conditional imports are not supported... Best I can think of atm would be to use reflection as you would need to in java...

An ast transform could also be used here to tag the class and wrap the code that uses the missing class with the required reflection code


I guess a class loader could do the trick, but will be complicated.

Have you considered to use a shadow class and jsut deploy different jars?

Something like

//jdk 1.5
somethingelse extends this {
}

.

//jdk 1.6
somtheingelse extends that {
}

=> compile both to two different jar files, which you deploy on one system but not the other...

not perfect, but could work

...wait: if your libraries just differ in the package name, then you don't need a shadow class. Can't you move the one or the other in the same package?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号