class Student {
public String email="lilao#163.com";
//下面这个代码符合语法吗?这段代码有实际用处吗?
{System.out.println("Hello, I'm in Student: "+getClass());}
}
public class Test {
public static void main(String[] args){
new Student(){
//下面这两行代码在语法上面到底是什么一个说法,很不理解.
{System.out.println("hello, I'm in test: "+getClass());}
{System.out.println("hello, I'm in test, my name is:"+super.email );}
};
}
}
也许很多人认为这个只是奇淫巧计,没什么实际用处. 实际上不是的,这和匿名类很类似,通常我们直接通过这种方式,实现一个借口或者抽象类里面的一个方法,通过这样写代码可以很简单.
但是这个里面不同,它不是实现什么接口,或者方法.而是直接插入了一个代码块,并且直接执行,有点像静态方法块,其实这个就是非静态代码块.从这个链接里面,你可以看到更多. 在这只是再new对象时添加一个代码块,如果只是一次性使用,就很灵活.所以在测试的时候,就经常使用. (http://www.cnblogs.com/rgky/archive/2011/03/17/1986907.html)
在Jmock里面就经常有这种写法.比如你可以在下面的链接中找到很多类似的写法.
http://fly-hyp.iteye.com/blog/203094
context.checking(newExpectations(){
{
//另一种连续调用: 同个方法同样参数,调用多次返回值各不同,声明了调用次序
atLeast(1).of(dao).find(id1);
will(onConsecutiveCalls(
returnValue(user1),
returnValue(user2)));
}
});