Java 什么';这座建筑的名字是什么?

Java 什么';这座建筑的名字是什么?,java,Java,我在读一个我没有写的代码。我偶然发现了以下说法: context.checking(new org.jmock.Expectations() { { allowing(habilitationManager).hasRole(RoleDtoEnum.ROLE_NEWS); will(returnValue(true)); allowing(habilitationManager).hasRole(Ro

我在读一个我没有写的代码。我偶然发现了以下说法:

    context.checking(new org.jmock.Expectations() {
        {
            allowing(habilitationManager).hasRole(RoleDtoEnum.ROLE_NEWS);
            will(returnValue(true));
            allowing(habilitationManager).hasRole(RoleDtoEnum.ROLE_STAT);
            will(returnValue(true));
            allowing(habilitationManager).getUser();
            will(returnValue(getUserMock()));
            oneOf(parametreService).getParametre(PPP);
            will(returnValue(getMockPPP()));
        }
    });
我知道在第二个
{…}
中调用的方法是
期望
方法

  • 但是你怎么称呼这种代码编写呢
  • 特别是如何调用第二个
    {…}

这是一个匿名类,其中包含一个实例初始值设定项块。因此,要将两者分开:

// This is an anonymous class
Expectations expectations = new Expectations() {
    // Class body here
};

class Foo {

    // This is an instance initializer block in a normal class
    {
        System.out.println("You'll see this via either constructor");
    }

    Foo(int x) {}

    Foo(String y) {}
}

与实例变量初始值设定项同时以文本顺序在任何构造函数体之前隐式调用。

我认为这种类型的代码具有“流畅”的界面,更像英语(或类似DSL的语言)coding@Jon国际海事组织,阅读此类代码既简单又强大。为什么要将
org.jmock.expections
称为匿名类?在jMock项目中,它是一个具体的类。抱歉,如果我没有精确指出
Expectations
类的来源。@Alex
newexpectations(){…}
创建了Expectations子类的实例。它是匿名的子类。@fgb子类的实例???@Alex:是的。编译器生成的匿名类是
expections
的一个子类,当代码执行时,会创建该匿名类的一个实例。好了,伙计们,我不知道编译器有这么大的魔力:)