简体   繁体   English

如何使用带有Groovy闭包的构造函数参数实例化Java抽象类

[英]How to instantiate a Java abstract class with a constructor parameter with a groovy closure

I am trying to instantiate a Java abstract class from my Groovy code. 我试图从我的Groovy代码中实例化Java抽象类。 Considering the following Java abstract class (non relevant processing is stripped out from the class): 考虑以下Java抽象类(从该类中删除了不相关的处理):

public abstract class StackOverflow{
  public abstract String answerMe();
}

I can easily instantiate it in Groovy this way, and the call to answerMe() will trigger the correct output: 我可以通过Groovy轻松地实例化它,对answerMe()的调用将触发正确的输出:

StackOverflow stack = [answerMe : { "Answer" }] as StackOverflow

Now if I modify the StackOverflow class adding a String parameter in the constructor like this : 现在,如果我修改StackOverflow类,则在构造函数中添加一个String参数,如下所示:

public abstract class StackOverflowStr{
  public StackOverflowStr(String s){}
  public abstract String answerMe();
}

I don't really know how to instantiate my object, I tried a lot of thing, but I can't seem to find the right syntax, does someone got any clue ? 我真的不知道如何实例化我的对象,我做了很多事情,但是我似乎找不到正确的语法,有人知道吗?

Just for the record, and to be clear on wording: in all of these scenarios, you're not instantiating an abstract class. 仅作记录,并在措辞上明确:在所有这些情况下,您都没有实例化抽象类。

Abstract classes are classes that can never be instantiated. 抽象类是永远不能实例化的类。

You're instantiating a concrete anonymous class that extends an abstract class. 您正在实例化扩展抽象类的具体匿名类。 B-) B-)

You can instantiate it in classic Java style: 您可以用经典的Java风格实例化它:

StackOverflowStr stack = new StackOverflowStr("javaish"){
    String answerMe() {"answer"}
}

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

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