Groovy In Action 笔记 (8) -- MOP
/** * @author :ZackZhou * @date :Created in 2020/10/9 2:31 PM * @description : * All classes that are compiled by Groovy implement the GroovyObject interface * Again, you’re free to implement any such methods in your Groovy class to your liking. * If you don’t, then the Groovy compiler will insert a default implementation for you. * This default implementation is the same as if you’d inherit from GroovyObjectSupport, * which basically relays all calls to the metaclass. * * public abstract class GroovyObjectSupport implements GroovyObject { * public Object invokeMethod(String name, Object args) { * return getMetaClass().invokeMethod(this, name, args); * } * public Object getProperty(String property) { * return getMetaClass().getProperty(this, property); * } * public void setProperty(String property, Object newValue) { * getMetaClass().setProperty(this, property, newValue);* } * // more here... * } * * As soon as a class implements GroovyObject, the following rules apply: * ■ Every access to a property calls the getProperty() method.6 * ■ Every modification of a property calls the setProperty() method. * ■ Every call to an unknown method calls invokeMethod(). If the method is known, * invokeMethod() is only called if the class implements GroovyObject and the * marker interface GroovyInterceptable. * * * @modified By: * @version: */ // Groovy中提供的非JDK内置的方法,是通过 org.codehaus.groovy.runtime.DefaultGroovyMethods 这个类实现的 String myStr = "" myStr.metaClass println(myStr) /* // MOP pseudo code def mopInvoke(Object obj, String method, Object args) { if (obj instanceof GroovyObject) { return groovyObjectInvoke(obj, method, args) } registry.getMetaClass(obj.class).invokeMethod(obj, method, args) } def groovyObjectInvoke(Object obj, String method, Object args){ if (obj instanceof GroovyInterceptable) { return obj.metaClass.invokeMethod(method, args) } if (! obj.metaClass.respondsTo(method, args)) { return obj.metaClass.invokeMethod(method, args) } obj.metaClass.invokeMethod(obj, method, args) } // Default meta class pseudo code def invokeMethod(Object obj, String method, Object args) { if (obj.metaClass.respondsTo(method, args)) { return methodCall(obj, method, args) } if (methodMissingAvailable(obj)) { return obj.metaClass.methodMissing(method, args) } throw new MissingMethodException() } */