@Delegate类没有默认构造函数 [英] @Delegate class without default constructor
问题描述
如何在Groovy中为没有默认构造函数的类创建委托类?我想装饰JUnit的ResultPrinter,但得到关于缺少构造函数的错误。
How can I create a delegate class in Groovy for a class which doesn't have a default constructor? I would like to decorate JUnit's ResultPrinter but am getting an error about the missing constructor.
推荐答案
我不明白你的问题。我只是用Java的 Short
- 这也没有默认的构造函数。
I don't understand your issue. I just tried this with Java's Short
— which also does not have a default constructor.
除非你没有初始化委托对象,否则你会得到一个NPE。
Everything worked as expected, except if you didn't initialize the delegated object, you get an NPE.
有可能你是使用 @Delegate
错误地?委托不会修饰现有的类,它允许您在自己的类中使用现有的类方法。它就像 extend
,但没有类继承。
Is it possible you are using @Delegate
incorrectly? Delegate doesn't decorate existing classes, it allows you to use an existing classes methods in your own class. It's like extend
, but without the class inheritance.
示例代码:
class Foo {
@Delegate Short num
String bar
String toString() { "$bar: $num" }
}
def f = new Foo(bar: 'bob', num: 34 as Short)
println f // OK
println f.doubleValue() // OK
f = new Foo()
println f.doubleValue() // NPE
(或者,提供一些有用的信息,例如实际的错误和堆栈跟踪以及示例代码,将会为您提供更有用的响应。)
(Alternatively, providing some useful information, such as the actual error and stacktrace, and example code, will get you more useful responses.)
这篇关于@Delegate类没有默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!