开发者

Is it possible to automatically preload user classes into the groovy interpreter?

Is there any way to automatically load user classes in the groovy interpreter, the way System.out is automatically loaded (so you don't have to import System.o开发者_Go百科ut to use println)? I want to be able to write scripts that employ custom classes and run the scripts in the groovy interpreter without having to import all the classes all the time.


Yep, you just need to create a profile/rc file. Just create a file at ~/.groovy/groovysh.profile and put your imports in there. You'll also want to make sure that any additional classes you want to include are part of your CLASSPATH.

ex: ~/.groovy/groovysh.profile:

import org.apache.commons.lang.StringUtils

println "in groovysh.profile"

Then run groovysh and use a method from StringUtils:

% groovysh
in groovysh.profile
Groovy Shell (1.7.3, JVM: 1.6.0_20)
Type 'help' or '\h' for help.
---------------------------------------------------------------------------------------------------------------------------------
groovy:000> StringUtils.isWhitespace("    ")
===> true
groovy:000> 

You can see that the import is in place (and that it also printed out the println I had in the profile. This example will only work if you've got the commons-lang jar file is in your classpath.

See the Groovy Shell page for more details.


Groovy adds some methods to Object, including methods like println and printf that you'd expect on printWriters. They implicitly use System.out. This is actually how groovy makes if feel like System.out is globally available.

If you want to import a set of classes by default, so they can be used without specifying the full package name, Ted's comment about groovysh.profile applies.

However, if you want a specific object, like System.out, global available so its methods can be called without referencing the object, then you can add some dynamic methods to Object. For example, to make the logging methods of the default global JDK logger globally available:

Object.metaClass.info = { String message ->
    java.util.logging.Logger.global.info(message)
}
Object.metaClass.warning = { String message ->
    java.util.logging.Logger.global.warning(message)
}
Object.metaClass.severe = { String message ->
    java.util.logging.Logger.global.severe(message)
}
etc...

Once those methods are applied to the base Object metaClass, any object can call info("message") and have it logged, effectively making Logger.global available in the same way System.out is.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜