有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

groovy中的java匿名内部类

我正在研究groovy wicket集成,在编写事件处理程序时,缺少匿名内部类似乎是一个问题。 有没有更常规的方法来编写这段代码

import org.apache.wicket.PageParameters
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.link.Link
import org.apache.wicket.markup.html.WebPage


/**
 * Homepage
 */
class HomePage extends WebPage {


    public HomePage(final PageParameters parameters) {

        // Add the simplest type of label
        add(new Label("message", "Wicket running!"));   
        def link1 = new ClickHandler("link1") //in java, defined inline
        add(link1);
    }   
}

class ClickHandler extends Link{

    ClickHandler(String id) {
        super(id);
    }

    void onClick(){println "Hi"}
}

共 (5) 个答案

  1. # 3 楼答案

    Groovy 1.7及更高版本支持匿名内部类。参见groovy 1.7release notes

  2. # 4 楼答案

    我可能错了,但这不正是WickeBuilder试图解决的问题吗:

    The Wicket Builder utility implements a Groovy Builder for constructing Wicket Component trees.

    While using the builder makes building Component trees easier and more clear to the reader, the original driver was the fact that Groovy does not allow anonymous inner classes. Wicket relies on overriding methods to provide custom functionality for many Component types. Groovy can be used to code Wicket page classes, but each class that is overridden needs a named class definition. Possible, but clunky.

    The WicketBuilder simulates these overrides with named Closures. Closures are, essentially, portable code blocks. Under the hood, the builder creates dynamic class overrides and runs the closures when the named method is called.

    [...]