【问题标题】:Gradle: extend DLS of existing typeGradle:扩展现有类型的 DLS
【发布时间】:2017-01-20 20:14:36
【问题描述】:

我想为现有类型添加一个函数,在我的例子中是NativeLibrarySpec

我尝试使用gradle extensions,它即将工作,但现在我想概括它以便能够使用它,就像它是NativeLibrarySpec 的 DSL 的标准功能一样。 问题是我只能在它的配置(包含我的函数的块)之后访问实例,所以它失败了,因为它在我能够链接它之前尝试调用specialConfig...

这里是代码(不要在意这个例子是针对本地软件 C++ 的):

// File: build.gradle
apply plugin: 'cpp'

class SpecialConfig {
    NativeComponentSpec componentSpec

    SpecialConfig(NativeComponentSpec componentSpec) {
        this.componentSpec = componentSpec
    }

    def something(boolean enabled) {
        componentSpec.sources {
            cpp {
                // Some important stuffs
            }
        }
    }
}

model {
    components {
        main(NativeLibrarySpec) {
            // How to bring this out ??
            project.extensions.create('specialConfig', SpecialConfig, it)

            // This is the new functionality I want to use
            specialConfig {
                something(true)
            }
        }
    }
}

这是另一个示例,但它仅适用于项目。* https://dzone.com/articles/gradle-goodness-extending-dsl

【问题讨论】:

    标签: java c++ gradle dsl


    【解决方案1】:

    你可以试试这个吗

    plugins {
        id 'cpp'
    }
    
    class SpecialConfig {
        // no need to pass this to the constructor we can just make it a
        // method arg instead
        SpecialConfig() {
        }
    
        // manipulate spec as desired
        def something(NativeComponentSpec spec, boolean enabled) {
            println "Hello something!"
            spec.sources {
                cpp {
                    // Some important stuffs
                }
            }
        }
    }
    
    // add your extension earlier
    project.extensions.create('specialConfig', SpecialConfig)
    model {
        components {
            main(NativeLibrarySpec) { mySpec ->
                // we can call our extension via the project
                project.specialConfig { config ->
                    // our closure is handed an instance of the class
                    // on that we can call methods
                    config.something(mySpec, true)
                }
                // or more simply we could make it a one liner
                project.specialConfig.something(mySpec, true)
            }
        }
    }
    

    输出:

    $ gradle build
    Configuration on demand is an incubating feature.
    Hello something!
    :linkMainSharedLibrary UP-TO-DATE
    :mainSharedLibrary UP-TO-DATE
    :createMainStaticLibrary UP-TO-DATE
    :mainStaticLibrary UP-TO-DATE
    :assemble UP-TO-DATE
    :check UP-TO-DATE
    :build UP-TO-DATE
    
    BUILD SUCCESSFUL
    
    Total time: 1.104 secs
    

    【讨论】:

    • 感谢您的宝贵时间 :) 不幸的是,我正在寻找一种无需传递任何参数的方法,代码应该看起来很流畅
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多