简体   繁体   English

使用Groovy作为脚本语言

[英]Using Groovy as a scripting language

I prefer to use scripting languages for short tasks, anything such as a really simple http bot, bulk importing/exporting data to/from somewhere, etc etc... Basic throw-away scripts and simple stuff. 我更喜欢使用脚本语言来完成简短的任务,比如一个非常简单的http机器人,批量导入/导出数据到某个地方等等......基本的丢弃脚本和简单的东西。 The point being, that a scripting language is just an efficient tool to write quick programs with. 关键是,脚本语言只是编写快速程序的有效工具。 As for my understanding of Groovy at this point... 至于我在这一点上对Groovy的理解......

If you were to program in Groovy, and you wan't to write a quick script, wouldn't you be forced to going back to regular java syntax (and we know how that can be convoluted compared to a scripting language) in order to do anything more complicated? 如果你要在Groovy中编程,并且你不想写一个快速的脚本,你不会被迫回到常规的java语法(我们知道如何与脚本语言相比可以复杂化)以便做更复杂的事情? For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient? 例如,如果我想做一些http脚本,我不会直接使用java语法来调用Commons HttpClient吗? To me, the point of a scripting language is for quickly typed and less forced constructs. 对我而言,脚本语言的意义在于快速键入和强制构造。 And here is another thing, it doesn't seem that there is any incentive for groovy based libraries to be developed when there are already so many good java one's out there, thus making groovy appear to be a Java dependent language with minor scripting features. 这是另一回事,似乎没有任何动机可以开发基于groovy的库,因为已经有这么多优秀的Java,因此使groovy看起来是一种具有次要脚本功能的Java依赖语言。

So right now I am wondering if I could switch to Groovy as a scripting language or continue to use a more common scripting language such as Perl, Python or Ruby. 所以现在我想知道我是否可以转换为Groovy作为脚本语言或继续使用更常见的脚本语言,如Perl,Python或Ruby。

@Zombies, let me show you a quick example from a script I wrote recently: @Zombies,让我向您展示我最近写的一个脚本的快速示例:

def fetch(build, toFile) {
    new FTPClient().with {
        connect ftpServer
        enterLocalPassiveMode()
        login ftpUser, ftpPassword
        changeWorkingDirectory "/var/staging/revision-${build}"
        fileType = FTPClient.BINARY_FILE_TYPE
        toFile.withOutputStream { ostream -> 
            retrieveFile "build-${build}.zip", ostream 
        }
        disconnect()
    }
}

It uses commons-net API, but I think you would agree that it has a much clearer syntax than comparable Java program. 它使用commons-net API,但我认为你会同意它比同类Java程序有更清晰的语法。 So I don't think using the Java APIs defeats the purpose of having a scripting language. 因此,我不认为使用Java API会破坏使用脚本语言的目的。 Furthermore, it helps you leverage your existing knowledge of the Java APIs, so is a very pragmatic approach. 此外,它可以帮助您利用Java API的现有知识,因此是一种非常实用的方法。

One goal of Groovy is to have transparent interoperability with Java. Groovy的一个目标是与Java实现透明的互操作性。 Groovy is by design "a Java dependent language with scripting features". Groovy是设计“具有脚本功能的Java依赖语言”。 However, I don't think that these features are minor - Groovy has many features that are not found in static programming languages (such as Java). 但是,我不认为这些功能很小 - Groovy有许多静态编程语言(如Java)中没有的功能。

To summarize: If you don't care at all about Java, then use a more general-purpose scripting language, such as Python or Perl. 总结一下:如果您根本不关心Java,那么请使用更通用的脚本语言,例如Python或Perl。 If you want to use the Java code-base in a script-ish way, Groovy is a good option. 如果您想以脚本方式使用Java代码库,Groovy是一个不错的选择。

Groovy can be quite handy for scripting. Groovy可以非常方便地编写脚本。 Recently I needed a script to fetch Maven dependencies into a lib directory and ended up with a groovy script. 最近我需要一个脚本来将Maven依赖项提取到lib目录中,最后得到一个groovy脚本。 This snippet parses a pom and gives you a list of jars. 这个片段解析一个pom并给你一个罐子列表。 Pretty sweet for XML parsing! 非常适合XML解析!

#!/usr/bin/env groovy
def pom = new XmlSlurper().parse('pom.xml')
def repo = "${System.env.HOME}/.m2/repository"

pom.dependencies.dependency.each { dep ->
    def jarName = "${dep.artifactId}-${dep.version}.jar"
    def groupPath = dep.groupId.text().replaceAll('\\.', '/')
    def jarPath = "${repo}/${groupPath}/${dep.artifactId}/${dep.version}"
    println "$jarPath/$jarName"
}

For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient? 例如,如果我想做一些http脚本,我不会直接使用java语法来调用Commons HttpClient吗?

You would be "right back at using Commons HttpClient", but you would invoke it using Groovy syntax, not Java syntax. 您将“直接使用Commons HttpClient”,但您可以使用Groovy语法而不是Java语法来调用它。 Groovy syntax is a lot more compact than Java syntax and therefore better suited for scripting. Groovy的语法是很多比Java的语法更紧凑,因此更适合于脚本。 In other words, using Java libraries in Groovy takes a lot less code than using Java libraries in Java. 换句话说,使用Groovy中的Java库比使用Java中的Java库需要的代码少得多。

it doesn't seem that there is any incentive for groovy based libraries to be developed when there are already so many good java one's out there 似乎没有任何动机可以开发基于groovy的库,因为已经有那么多优秀的java出现了

Rather than developing an entirely new library, a Groovy library author will often provide a "Groovier" API to an existing Java library. Groovy库作者不是开发一个全新的库,而是经常为现有的Java库提供“Groovier”API。 Examples include the Hibernate builder provided by Grails, and the HTTP Builder (which delegates to Commons HttpClient). 示例包括Grails提供的Hibernate构建器和HTTP Builder (委托给Commons HttpClient)。

These Groovy APIs provide a more compact and idiomatic alternative to using the Java API directly. 这些Groovy API提供了直接使用Java API的更紧凑和惯用的替代方法。

Groovy "out of the box" replaces a large number of common classes with groovier versions or language constructs, including classes for XML, HTTP requests, accessing SQL databases and regular expressions. Groovy“开箱即用”用更长的版本或语言结构替换了大量的公共类,包括XML,HTTP请求,访问SQL数据库和正则表达式的类。 For most scripting tasks, you won't have to use Java libraries at all (although you'll still have that option). 对于大多数脚本任务,您根本不必使用Java库(尽管您仍然可以使用该选项)。 But if your script uses bare Java libraries, you'll be much farther ahead with Groovy over straight Java. 但是如果你的脚本使用裸Java库,那么使用Groovy比直接Java要远得多。 Where Groovy shines is in the "glue" code, such as setting up data structures and file I/O. Groovy闪耀的地方是“胶水”代码,例如设置数据结构和文件I / O.

The map and list allow you to create Java compatible Lists and Maps; 地图和列表允许您创建Java兼容的列表和地图; regular Java objects that work with Java classes. 与Java类一起使用的常规Java对象。 Groovy often turns a multi-line Java method invokation with variable declarations and initalization into a one-liner. Groovy经常将具有变量声明和初始化的多行Java方法调用转换为单行。

Consider this short snippet to load an entire file into a String: 考虑这个简短的片段将整个文件加载到String中:

def fileContents = new File(filename).text

versus

String fileContents = "";
try {
    BufferedReader reader = new BufferedReader(new FileInputStream(filename));
    String line = null;
    while ((line = reader.readLine()) != null) {
        text = text + line + "\n";
    }
} catch (IOException e) {
    e.printStackTrace();
}

Exception handling is often not an important consideration in scripts and it can be conveniently ignored. 在脚本中,异常处理通常不是一个重要的考虑因素,可以方便地忽略它。

Groovy's main strength as a scripting language is accessing the enormous library of Java code that's out there directly and conveniently. Groovy作为脚本语言的主要优势是可以直接方便地访问庞大的Java代码库。 If that's not your need, groovy still provides a scripting environment about as rich as other languages such as perl, python or ruby. 如果这不是您的需要,groovy仍然提供与其他语言(如perl,python或ruby)一样丰富的脚本环境。

Groovy rocks, once you get a hang of the very tight syntax, you start to use it for a lot of things you've just done "the slow way". Groovy的岩石,一旦你掌握了非常严格的语法,你就会开始使用它来完成很多你刚刚做过的“缓慢的方式”。

The other day I was in a discussion which somehow got to wondering how many chars we have in a GUID in one of our systems. 有一天,我正在进行一次讨论,不知道我们在一个系统的GUID中有多少个字符。 Rather than just count the digits, it was easier to just do this: 而不是仅仅计算数字,这样做更容易:

def str = '92228498-6A2F-DBA2-7A2C-F54B9E607E3A'
int num = 0
str.each {
    num++
}
println num

Whack that in a local or shared scripts directory and it'll be there for the future. 在本地或共享脚本目录中发现它将会存在于未来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM