简体   繁体   English

Groovy脚本编译为一个类

[英]Groovy script compiles to a class

From this answer , I learnt that, every Groovy script compiles to a class that extends groovy.lang.Script class 从这个答案中 ,我了解到,每个Groovy脚本都编译为扩展groovy.lang.Script类的类。

Below is a test groovy script written for Jenkins pipeline in Jenkins editor. 以下是在Jenkins编辑器中为Jenkins管道编写的测试groovy脚本。

node('worker_node'){
    print "***1. DRY principle***"

    def list1 = [1,2,3,4]
    def list2 = [10,20,30,40]

    def factor = 2

    def applyFactor =  {e -> e * factor}

    print(list1.each(applyFactor))
    print(list2.each(applyFactor))



    print "***2. Higher order function***"

    def foo = { value, f ->  f(value *2) }

    foo(3, {print "Value is $it"})

    foo(3){
        print "Value is $it"
    }
}

How to compile this groovy script to see the class generated(source code)? 如何编译该常规脚本以查看生成的类(源代码)?

The class generated is bytecode , not source code. 生成的类是字节码 ,而不是源代码。 The source code is the Groovy script. 源代码是Groovy脚本。

If you want to see something similar to what the equivalent Java source code would look like, use groovyc to compile the script as usual, and then use a Java decompiler to produce Java source ( this question's answers lists a few). 如果您希望看到与等效的Java源代码相似的内容,请像往常一样使用groovyc编译脚本,然后使用Java反编译器生成Java源代码( 此问题的答案列出了一些)。

That's subject to the usual caveats on decompiled code, of course. 当然,这要遵守反编译代码的一般警告。 High-level information is lost in the process of compiling. 高级信息在编译过程中会丢失。 Decompilers have to guess a bit to figure out the best way to represent what might have been in the original source. 反编译器必须猜测一下,才能找到表示原始源中可能存在的最佳方法。 For instance, what was a for loop in the original code may end up being decompiled as a while loop instead. 例如,原始代码中的for循环可能最终会被反编译为while循环。

groovy in jenkins pipeline is a Domain Specific Language. 詹金斯管道中的groovy是一种领域特定语言。 It's not a plain groovy. 这不是一个普通的习惯。

However if you remove node(){ } then it seems to be groovy in your case. 但是,如果删除node(){ }那么您的情况似乎很糟。

and you can run it in groovyconsole or compile to class with groovyc 你可以在运行groovyconsole或编译成类groovyc

just download a stable groovy binary and extract it. 只需下载稳定的groovy二进制文件并将其解压缩即可。

if you have java7 or java8 on your computer - you can run groovyconsole and try your code there. 如果您的计算机上装有java7或java8,则可以运行groovyconsole并在那里尝试代码。

with Ctrl+T you can see the actual class code generated for your script. 使用Ctrl+T您可以看到为脚本生成的实际类代码。

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

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