求解一个java语法.关于双花括号的.

CUG122032 2008-11-26 09:39:16
context.checking(new Expectations() {{
allowing(appDA).getAppbyApiKey("invalidKey"); will(returnValue(null));
allowing(appDA).getAppbyApiKey("testValidKey"); will(returnValue(app));
allowing(accountDA).insertFrob(with(any(Frob.class)));
}});


请帮我讲解一下上面的语法,最好能讲透一点.多谢.
...全文
318 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
hebo_thu 2010-02-26
  • 打赏
  • 举报
回复
就是一匿名内部类,里面有一个实例初始化块。
chensjmail 2008-11-26
  • 打赏
  • 举报
回复

首先
这是一个匿名内部类,
extends Expectations
而这个内层的{}号是一个匿名的构造器,

{
allowing(appDA).getAppbyApiKey("invalidKey"); will(returnValue(null));
allowing(appDA).getAppbyApiKey("testValidKey"); will(returnValue(app));
allowing(accountDA).insertFrob(with(any(Frob.class)));
}

这个构造器不能使用super();和this();(包括有参数的)

外层{}是类的定义区,和其它的类编码没什么区别
hbwhwang 2008-11-26
  • 打赏
  • 举报
回复
new Expectations() {}
-----------
这是匿名类Anonymous Class的写法,Expectations是一个接口或者纯虚类或者普通类,就其在代码的定义来看,应该不是接口而是类。

{}里面的{}
是对象初始化代码,先于构造方法执行

这种写法类似于:

Class AnonymousExpectations extends Expectations{
AnonymousExpectations(){
}
//这里的代码先于AnonymousExpectations 构造方法执行
{
allowing(appDA).getAppbyApiKey("invalidKey");
will(returnValue(null));
allowing(appDA).getAppbyApiKey("testValidKey");
will(returnValue(app));
allowing(accountDA).insertFrob(with(any(Frob.class)));
}
}
............
context.checking(new AnonymousExpectations());
alvin__Gao 2008-11-26
  • 打赏
  • 举报
回复
关注
lc7cl 2008-11-26
  • 打赏
  • 举报
回复
同2楼
CUG122032 2008-11-26
  • 打赏
  • 举报
回复
顶下.
jiaxy917 2008-11-26
  • 打赏
  • 举报
回复
关注
yyy6210 2008-11-26
  • 打赏
  • 举报
回复
我觉得是个对象初始化块

外边的是个匿名内部类
里面那个括号是对象初始化块,要先执行

参考~~~
jcyan 2008-11-26
  • 打赏
  • 举报
回复
context.checking(a)//a可能是整数、字符串、数组等等
a = new Expectations(){b}//此时a为一个对象(new Expectations()),它的实现是b
b = {allowing(appDA).getAppbyApiKey("invalidKey"); will(returnValue(null));…}//b包含了一些方法什么什么的
CUG122032 2008-11-26
  • 打赏
  • 举报
回复
最好每种语法元素都能给一下详细的资料链接:)

62,610

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧