代码之家  ›  专栏  ›  技术社区  ›  mike rodent

创建一个新的“飞行”类?

  •  2
  • mike rodent  · 技术社区  · 7 年前

    ……尤其是在groovy中(因此标记)?

    在爪哇,你不能这么做…但在动态语言(如python)中,您通常可以。

    尝试做类似于 given Spock功能块(即测试方法)在Eclipse中遇到:

    groovy:此处不需要类定义。请在定义类 一个合适的地方,或者尝试使用块/闭包代替。

    ……一个“合适”的地方显然是在特性之外的。这将是笨拙的,而不是groovy。使用了几个月的groovy之后,现在我感觉到什么时候groovy应该提供一些groovy。

    所以说我想延长我的 abstract AbstractFoo 并生成新的子类 Foo 在我的特性中,是否有任何方法可以“使用块/闭包”来实现类似的功能?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Szymon Stepniak    7 年前

    AbstractFoo

    abstract class AbstractFoo {
        void bar() {
            println text()
        }
    
        abstract String text()
    }
    
    def foo1 = new AbstractFoo() {
        @Override
        String text() {
            return "Hello, world!"
        }
    }
    
    def foo2 = new AbstractFoo() {
        @Override
        String text() {
            return "Lorem ipsum dolor sit amet"
        }
    }
    
    foo1.bar()
    foo2.bar()
    

    foo1 foo2 text() bar()

    Hello, world!
    Lorem ipsum dolor sit amet
    

    def foo3 = { "test 123" } as AbstractFoo
    foo3.bar()
    

    abstract class AbstractFoo {
        abstract String text()
        abstract int number()
        void bar() {
            println "text: ${text()}, number: ${number()}"
        }
    }
    
    def foo = [
        text: { "test 1" },
        number: { 23 }
    ] as AbstractFoo
    
    foo.bar()
    

    Map<String, Closure<?>>

    text: test 1, number: 23
    

    GroovyClassLoader.parseClass(input)

    abstract class AbstractFoo {
        void bar() {
            println text()
        }
    
        abstract String text()
    }
    
    def newClassDefinitionAsString = '''
    class Foo extends AbstractFoo {
        String text() {
            return "test"
        }
    }
    '''
    
    def clazz = new GroovyClassLoader(getClass().getClassLoader()).parseClass(newClassDefinitionAsString)
    
    def foo = ((AbstractFoo) clazz.newInstance())
    
    foo.bar()
    

    Foo test()

    given:

    class MySpec extends Specification {
    
        def "should do something"() {
            given:
            Class<?> clazz = Foo.class
    
            when:
            //....
    
            then:
            ///....
        }
    
        private static class Foo extends AbstractFoo  {
    
        }
    }