?? metaclassimpl.java
字號:
/*
$Id: MetaClassImpl.java 4669 2007-01-02 19:35:47Z blackdrag $
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact info@codehaus.org.
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package groovy.lang;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.classgen.BytecodeHelper;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.Phases;
import org.codehaus.groovy.runtime.CurriedClosure;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.DefaultMethodKey;
import org.codehaus.groovy.runtime.GroovyCategorySupport;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.MetaClassHelper;
import org.codehaus.groovy.runtime.MethodClosure;
import org.codehaus.groovy.runtime.MethodKey;
import org.codehaus.groovy.runtime.NewInstanceMetaMethod;
import org.codehaus.groovy.runtime.NewStaticMetaMethod;
import org.codehaus.groovy.runtime.ReflectionMetaMethod;
import org.codehaus.groovy.runtime.Reflector;
import org.codehaus.groovy.runtime.TransformMetaMethod;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.codehaus.groovy.runtime.wrappers.Wrapper;
import org.objectweb.asm.ClassVisitor;
/**
* Allows methods to be dynamically added to existing classes at runtime
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author Guillaume Laforge
* @author Jochen Theodorou
* @version $Revision: 4669 $
* @see groovy.lang.MetaClass
*/
public class MetaClassImpl extends MetaClass {
protected MetaClassRegistry registry;
private ClassNode classNode;
private Map classMethodIndex = new HashMap();
private Map classMethodIndexForSuper;
private Map classStaticMethodIndex = new HashMap();
private Map classPropertyIndex = new HashMap();
private Map classPropertyIndexForSuper = new HashMap();
private Map staticPropertyIndex = new HashMap();
private Map listeners = new HashMap();
private Map methodCache = Collections.synchronizedMap(new HashMap());
private Map staticMethodCache = Collections.synchronizedMap(new HashMap());
private MetaMethod genericGetMethod;
private MetaMethod genericSetMethod;
private List constructors;
private List allMethods = new ArrayList();
private List interfaceMethods;
private Reflector reflector;
private boolean initialized;
// we only need one of these that can be reused over and over.
private MetaProperty arrayLengthProperty = new MetaArrayLengthProperty();
private final static MetaMethod AMBIGOUS_LISTENER_METHOD = new MetaMethod(null,null,new Class[]{},null,0);
private static final Object[] EMPTY_ARGUMENTS = {};
private List newGroovyMethodsList = new LinkedList();
public MetaClassImpl(MetaClassRegistry registry, final Class theClass) {
super(theClass);
this.registry = registry;
constructors = (List) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return Arrays.asList (theClass.getDeclaredConstructors());
}
});
}
private void fillMethodIndex() {
LinkedList superClasses = getSuperClasses();
// let's add all the base class methods
for (Iterator iter = superClasses.iterator(); iter.hasNext();) {
Class c = (Class) iter.next();
addMethods(c);
}
Set interfaces = new HashSet();
makeInterfaceSet(theClass,interfaces);
inheritMethods(superClasses,classMethodIndex);
inheritInterfaceMethods(interfaces);
copyClassMethodIndexForSuper();
connectMultimethods(superClasses);
populateInterfaces(interfaces);
removeMultimethodsOverloadedWithPrivateMethods();
replaceWithMOPCalls();
}
private LinkedList getSuperClasses() {
LinkedList superClasses = new LinkedList();
for (Class c = theClass; c!= null; c = c.getSuperclass()) {
superClasses.addFirst(c);
}
if (theClass.isArray() && theClass!=Object[].class && !theClass.getComponentType().isPrimitive()) {
superClasses.addFirst(Object[].class);
}
return superClasses;
}
private void removeMultimethodsOverloadedWithPrivateMethods() {
Map privates = new HashMap();
MethodIndexAction mia = new MethodIndexAction() {
public List methodNameAction(Class clazz, String methodName, List methods) {
boolean hasPrivate=false;
for (Iterator iter = methods.iterator(); iter.hasNext();) {
MetaMethod method = (MetaMethod) iter.next();
if (method.isPrivate() && clazz == method.getDeclaringClass()) {
hasPrivate = true;
break;
}
}
if (!hasPrivate) return null;
// We have private methods for that name, so remove the
// multimethods. That is the same as in our index for
// super, so just copy the list from there. It is not
// possible to use a pointer here, because the methods
// in the index for super are replaced later by MOP
// methods like super$5$foo
methods.clear();
methods.addAll((Collection) ((Map) classMethodIndexForSuper.get(clazz)).get(methodName));
return methods;
}
public boolean replaceMethodList() {return false;}
};
mia.iterate(classMethodIndex);
}
private void replaceWithMOPCalls() {
// no MOP methods if not a child of GroovyObject
if (!GroovyObject.class.isAssignableFrom(theClass)) return;
final Map mainClassMethodIndex = (Map) classMethodIndex.get(theClass);
class MOPIter extends MethodIndexAction {
boolean useThis;
public boolean skipClass(Class clazz) {
return !useThis && clazz==theClass;
}
public void methodListAction(Class clazz, String methodName, MetaMethod method, List oldList, List newList) {
String mopName = getMOPMethodName(method.getDeclaringClass(), methodName,useThis);
List matches = (List) mainClassMethodIndex.get(mopName);
if (matches==null) {
newList.add(method);
return;
}
matches = new ArrayList(matches);
MetaMethod matchingMethod = removeMatchingMethod(matches,method);
if (matchingMethod==null) {
newList.add(method);
return;
} else {
newList.add(matchingMethod);
}
}
}
MOPIter iter = new MOPIter();
// replace all calls for super with the correct MOP method
iter.useThis = false;
iter.iterate(classMethodIndexForSuper);
// replace all calls for this with the correct MOP method
iter.useThis = true;
iter.iterate(classMethodIndex);
}
private String getMOPMethodName(Class declaringClass, String name, boolean useThis) {
int distance = 0;
for (;declaringClass!=null; declaringClass=declaringClass.getSuperclass()) {
distance++;
}
return (useThis?"this":"super")+"$"+distance+"$"+name;
}
private void copyClassMethodIndexForSuper() {
classMethodIndexForSuper = new HashMap(classMethodIndex.size());
for (Iterator iter = classMethodIndex.entrySet().iterator(); iter.hasNext();) {
Map.Entry cmiEntry = (Map.Entry) iter.next();
Map methodIndex = (Map) cmiEntry.getValue();
Map copy = new HashMap (methodIndex.size());
for (Iterator iterator = methodIndex.entrySet().iterator(); iterator.hasNext();) {
Map.Entry mEntry = (Map.Entry) iterator.next();
copy.put(mEntry.getKey(), new ArrayList((List) mEntry.getValue()));
}
classMethodIndexForSuper.put(cmiEntry.getKey(),copy);
}
}
private void inheritInterfaceMethods(Set interfaces) {
// add methods declared by DGM for interfaces
List methods = registry.getInstanceMethods();
for (Iterator iter = methods.iterator(); iter.hasNext();) {
Method element = (Method) iter.next();
Class dgmClass = element.getParameterTypes()[0];
if (!interfaces.contains(dgmClass)) continue;
NewInstanceMetaMethod method = new NewInstanceMetaMethod(createMetaMethod(element));
if (! newGroovyMethodsList.contains(method)){
newGroovyMethodsList.add(method);
}
Map methodIndex = (Map) classMethodIndex.get(theClass);
List list = (List) methodIndex.get(method.getName());
if (list == null) {
list = new ArrayList();
methodIndex.put(method.getName(), list);
list.add(method);
} else {
addMethodToList(list,method);
}
}
methods = registry.getStaticMethods();
for (Iterator iter = methods.iterator(); iter.hasNext();) {
Method element = (Method) iter.next();
Class dgmClass = element.getParameterTypes()[0];
if (!interfaces.contains(dgmClass)) continue;
addNewStaticMethod(element);
}
}
private void populateInterfaces(Set interfaces){
Map currentIndex = (Map) classMethodIndex.get(theClass);
Map index = new HashMap();
copyNonPrivateMethods(currentIndex,index);
for (Iterator iter = interfaces.iterator(); iter.hasNext();) {
Class iClass = (Class) iter.next();
Map methodIndex = (Map) classMethodIndex.get(iClass);
if (methodIndex==null || methodIndex.size()==0) {
classMethodIndex.put(iClass,index);
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -