【发布时间】:2014-03-08 15:35:10
【问题描述】:
我正在读一本书“Venkat Subramaniam 编写的 Groovy 2 编程”,在那本书的第 12 章 [使用 MOP 的拦截方法] 下,他给出了 “如果 Groovy 对象实现了 GroovyInterceptable 接口,那么它的调用方法()是 调用它的所有方法调用。”。我测试了这个及其工作。我的问题是,如果我在该类上实现 invokeMethod(),那么它将被调用,否则调用默认的 invokeMethod,但默认的 invokeMethod() 是在我的实现 GroovyInterceptable 接口的类中不存在,那么这个概念是如何起作用的。
实现了带有 GroovyInterceptable 接口的类
class InterceptingMethodsUsingGroovyInterceptableExample {
static void main(String... args){
Phone phone = new Phone()
phone.mobileNumber = 9755055420
phone.mobileType = "Android"
println phone.save()
Phone phone2 = new Phone()
phone2.mobileNumber = 9755055420
//phone2.mobileType = "Android"
println phone2.save()
Phone phone3 = new Phone()
phone3.mobileNumber = 9755055420
println phone3.isValid()
}
}
class Phone implements GroovyInterceptable {
String mobileType;
Long mobileNumber
def isValid(){
def returnValue = false
if ((mobileType)&& (mobileNumber?.toString()?.length() == 10) )
returnValue = true
returnValue
}
def save(){
return "Saved"
}
}
Output :
Saved
Saved
false
手机的JAD反编译代码:
public class Phone implements GroovyInterceptable{
private String mobileType;
private Long mobileNumber;
public Phone()
{
Phone this;
CallSite[] arrayOfCallSite = $getCallSiteArray();
MetaClass localMetaClass = $getStaticMetaClass();
this.metaClass = localMetaClass;
}
public Object isValid()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();Object returnValue = Boolean.valueOf(false);
boolean bool1;
boolean bool2;
if ((!BytecodeInterface8.isOrigInt()) || (!BytecodeInterface8.isOrigZ()) || (__$stMC) || (BytecodeInterface8.disabledStandardMetaClass()))
{
if (((DefaultTypeTransformation.booleanUnbox(this.mobileType)) && (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[0].callSafe(arrayOfCallSite[1].callSafe(this.mobileNumber)), Integer.valueOf(10))) ? 1 : 0) != 0)
{
bool1 = true;returnValue = Boolean.valueOf(bool1);
}
}
else if (((DefaultTypeTransformation.booleanUnbox(this.mobileType)) && (ScriptBytecodeAdapter.compareEqual(arrayOfCallSite[2].callSafe(arrayOfCallSite[3].callSafe(this.mobileNumber)), Integer.valueOf(10))) ? 1 : 0) != 0)
{
bool2 = true;returnValue = Boolean.valueOf(bool2);
}
return returnValue;return null;
}
public Object save()
{
CallSite[] arrayOfCallSite = $getCallSiteArray();return "Saved";return null;
}
static {}
public String getMobileType()
{
return this.mobileType;
}
public void setMobileType(String paramString)
{
this.mobileType = paramString;
}
public Long getMobileNumber()
{
return this.mobileNumber;
}
public void setMobileNumber(Long paramLong)
{
this.mobileNumber = paramLong;
}
}
【问题讨论】: