Since the groovy language is an extension of the Java language, it's hard to get involved with the Java language when we're using the groovy language, so we're doing a pure groovy language project like a grails project. We might use legacy Java classes and packages in groovy code, or for performance reasons, we have to use Java classes in the groovy language, and so on.
If we want to use the mop of the groovy language for Java classes, for example, we want to add a method to the object of a Java class during the run time. So what do we do?
For example, we have a Java class like the following:
//(Java代码)
public class Foo {
public String foo()
{
return "foo";
}
}
We can use the following method to add a method to its object during the runtime:
//(Groovy代码)
ExpandoMetaClass emc = new ExpandoMetaClass( Foo, false )
emc.hello = {"hello,world!"}
emc.initialize()
The code above is used to initialize a "Expandometaclass" object, then add a method, and then instantiate the object, as it does with the process of adding a method to the groovy object during the run time.
Next, our code is different from what we do with groovy objects, to wrap our Java class objects with the "Proxy" class, as follows:
def foo = new groovy.util.Proxy().wrap(new Foo())
And then there's the "Expandometaclass" object assigned to this object:
foo.setMetaClass(emc)
Finally, we can test the following:
println foo.hello()
The results of the operation are:
hello,world!
Similarly, for our Java class above, we can also use our custom interceptor to intercept its actions:
//(Groovy代码)
class FooInterceptor implements Interceptor{
Object beforeInvoke(Object a_object, String a_methodName, Object[] a_arguments)
{
if(a_methodName == 'foo')
{
println 'before invoking function foo'
}
}
boolean doInvoke()
{
return true
}
Object afterInvoke(Object a_object, String a_methodName, Object[] a_arguments, Object
a_result)
{
a_result
}
}
This interceptor is exactly the same as our custom interceptor that intercepts the groovy class. The same method is used for this interceptor:
//(Groovy代码)
def proxy = ProxyMetaClass.getInstance(Foo.class);
proxy.interceptor = new FooInterceptor()
proxy.use {
def foo = new Foo()
println foo.foo()
}
The results of the operation are:
before invoking function foo
foo