org.codehaus.groovy.reflection.CachedClass Java Examples

The following examples show how to use org.codehaus.groovy.reflection.CachedClass. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MetaMethodIndex.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean isMatchingMethod(MetaMethod aMethod, MetaMethod method) {
    if (aMethod==method) return true;
    CachedClass[] params1 = aMethod.getParameterTypes();
    CachedClass[] params2 = method.getParameterTypes();
    if (params1.length != params2.length) {
        return false;
    }

    boolean matches = true;
    for (int i = 0; i < params1.length; i++) {
        if (params1[i] != params2[i]) {
            matches = false;
            break;
        }
    }
    return matches;
}
 
Example #2
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void inheritInterfaceNewMetaMethods(Set<CachedClass> interfaces) {
    // add methods declared by DGM for interfaces
    for (CachedClass cls : interfaces) {
        MetaMethod[] methods = getNewMetaMethods(cls);
        for (MetaMethod method : methods) {
            boolean skip = false;
            // skip DGM methods on an interface if the class already has the method
            // but don't skip for GroovyObject-related methods as it breaks things :-(
            if (method instanceof GeneratedMetaMethod && !isAssignableFrom(GroovyObject.class, method.getDeclaringClass().getTheClass())) {
                for (Method m : theClass.getMethods()) {
                    if (method.getName().equals(m.getName())
                            // below not true for DGM#push and also co-variant return scenarios
                            //&& method.getReturnType().equals(m.getReturnType())
                            && MetaMethod.equal(method.getParameterTypes(), m.getParameterTypes())) {
                        skip = true;
                        break;
                    }
                }
            }
            if (!skip) {
                newGroovyMethodsSet.add(method);
                addMetaMethodToIndex(method, mainClassMethodHeader);
            }
        }
    }
}
 
Example #3
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void connectMultimethods(List<CachedClass> superClasses, CachedClass firstGroovyClass) {
    superClasses = DefaultGroovyMethods.reverse(superClasses);
    MetaMethodIndex.Header last = null;
    for (final CachedClass c : superClasses) {
        MetaMethodIndex.Header methodIndex = metaMethodIndex.getHeader(c.getTheClass());
        // We don't copy DGM methods to superclasses' indexes
        // The reason we can do that is particular set of DGM methods in use,
        // if at some point we will define DGM method for some Groovy class or
        // for a class derived from such, we will need to revise this condition.
        // It saves us a lot of space and some noticeable time
        if (last != null) metaMethodIndex.copyNonPrivateNonNewMetaMethods(last, methodIndex);
        last = methodIndex;

        if (c == firstGroovyClass)
            break;
    }
}
 
Example #4
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Fills the method index
 */
private void fillMethodIndex() {
    mainClassMethodHeader = metaMethodIndex.getHeader(theClass);
    LinkedList<CachedClass> superClasses = getSuperClasses();
    CachedClass firstGroovySuper = calcFirstGroovySuperClass(superClasses);

    Set<CachedClass> interfaces = theCachedClass.getInterfaces();
    addInterfaceMethods(interfaces);

    populateMethods(superClasses, firstGroovySuper);

    inheritInterfaceNewMetaMethods(interfaces);
    if (isGroovyObject) {
        metaMethodIndex.copyMethodsToSuper();

        connectMultimethods(superClasses, firstGroovySuper);
        removeMultimethodsOverloadedWithPrivateMethods();

        replaceWithMOPCalls(theCachedClass.mopMethods);
    }
}
 
Example #5
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MetaMethod getCategoryMethodMissing(Class sender) {
    List possibleGenericMethods = GroovyCategorySupport.getCategoryMethods("methodMissing");
    if (possibleGenericMethods != null) {
        for (Object possibleGenericMethod : possibleGenericMethods) {
            MetaMethod mmethod = (MetaMethod) possibleGenericMethod;
            if (!mmethod.getDeclaringClass().getTheClass().isAssignableFrom(sender))
                continue;

            CachedClass[] paramTypes = mmethod.getParameterTypes();
            if (paramTypes.length == 2 && paramTypes[0].getTheClass() == String.class) {
                return mmethod;
            }
        }
    }
    return null;
}
 
Example #6
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MetaMethod getCategoryMethodGetter(Class sender, String name, boolean useLongVersion) {
    List possibleGenericMethods = GroovyCategorySupport.getCategoryMethods(name);
    if (possibleGenericMethods != null) {
        for (Object possibleGenericMethod : possibleGenericMethods) {
            MetaMethod mmethod = (MetaMethod) possibleGenericMethod;
            if (!mmethod.getDeclaringClass().getTheClass().isAssignableFrom(sender))
                continue;

            CachedClass[] paramTypes = mmethod.getParameterTypes();
            if (useLongVersion) {
                if (paramTypes.length == 1 && paramTypes[0].getTheClass() == String.class) {
                    return mmethod;
                }
            } else {
                if (paramTypes.length == 0) return mmethod;
            }
        }
    }
    return null;
}
 
Example #7
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MetaMethod getCategoryMethodSetter(Class sender, String name, boolean useLongVersion) {
    List possibleGenericMethods = GroovyCategorySupport.getCategoryMethods(name);
    if (possibleGenericMethods != null) {
        for (Object possibleGenericMethod : possibleGenericMethods) {
            MetaMethod mmethod = (MetaMethod) possibleGenericMethod;
            if (!mmethod.getDeclaringClass().getTheClass().isAssignableFrom(sender))
                continue;

            CachedClass[] paramTypes = mmethod.getParameterTypes();
            if (useLongVersion) {
                if (paramTypes.length == 2 && paramTypes[0].getTheClass() == String.class) {
                    return mmethod;
                }
            } else {
                if (paramTypes.length == 1) return mmethod;
            }
        }
    }
    return null;
}
 
Example #8
Source File: Java9.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public MetaMethod transformMetaMethod(MetaClass metaClass, MetaMethod metaMethod, Class<?> caller) {
    if (!(metaMethod instanceof CachedMethod)) {
        return metaMethod;
    }

    CachedMethod cachedMethod = (CachedMethod) metaMethod;
    CachedClass methodDeclaringClass = cachedMethod.getDeclaringClass();

    if (null == methodDeclaringClass) {
        return metaMethod;
    }

    if (null == caller) {
        caller = ReflectionUtils.class; // "set accessible" are done via `org.codehaus.groovy.reflection.ReflectionUtils` as shown in warnings
    }

    return getOrTransformMetaMethod(metaClass, caller, cachedMethod);
}
 
Example #9
Source File: MetaClassHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * @param list   a list of MetaMethods
 * @param method the MetaMethod of interest
 * @return true if a method of the same matching prototype was found in the
 *         list
 */
public static boolean containsMatchingMethod(List list, MetaMethod method) {
    for (Object aList : list) {
        MetaMethod aMethod = (MetaMethod) aList;
        CachedClass[] params1 = aMethod.getParameterTypes();
        CachedClass[] params2 = method.getParameterTypes();
        if (params1.length == params2.length) {
            boolean matches = true;
            for (int i = 0; i < params1.length; i++) {
                if (params1[i] != params2[i]) {
                    matches = false;
                    break;
                }
            }
            if (matches) {
                return true;
            }
        }
    }
    return false;
}
 
Example #10
Source File: MetaClassRegistryImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void onModule(final ExtensionModule module) {
    if (moduleRegistry.hasModule(module.getName())) {
        ExtensionModule loadedModule = moduleRegistry.getModule(module.getName());
        if (loadedModule.getVersion().equals(module.getVersion())) {
            // already registered
            return;
        } else {
            throw new GroovyRuntimeException("Conflicting module versions. Module [" + module.getName() + " is loaded in version " +
                    loadedModule.getVersion() + " and you are trying to load version " + module.getVersion());
        }
    }
    moduleRegistry.addModule(module);
    // register MetaMethods
    List<MetaMethod> metaMethods = module.getMetaMethods();
    for (MetaMethod metaMethod : metaMethods) {
        CachedClass cachedClass = metaMethod.getDeclaringClass();
        List<MetaMethod> methods = map.computeIfAbsent(cachedClass, k -> new ArrayList<MetaMethod>(4));
        methods.add(metaMethod);
        if (metaMethod.isStatic()) {
            staticMethods.add(metaMethod);
        } else {
            instanceMethods.add(metaMethod);
        }
    }
}
 
Example #11
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private int findMatchingMethod(CachedMethod[] data, int from, int to, MetaMethod method) {
    for (int j = from; j <= to; ++j) {
        CachedMethod aMethod = data[j];
        CachedClass[] params1 = aMethod.getParameterTypes();
        CachedClass[] params2 = method.getParameterTypes();
        if (params1.length == params2.length) {
            boolean matches = true;
            for (int i = 0; i < params1.length; i++) {
                if (params1[i] != params2[i]) {
                    matches = false;
                    break;
                }
            }
            if (matches) {
                return j;
            }
        }
    }
    return -1;
}
 
Example #12
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * @return {@code false}: add method
 *         {@code null} : ignore method
 *         {@code true} : replace
 */
private static Boolean getMatchKindForCategory(MetaMethod aMethod, MetaMethod categoryMethod) {
    CachedClass[] params1 = aMethod.getParameterTypes();
    CachedClass[] params2 = categoryMethod.getParameterTypes();
    if (params1.length != params2.length) return Boolean.FALSE;

    for (int i = 0; i < params1.length; i++) {
        if (params1[i] != params2[i]) return Boolean.FALSE;
    }

    Class aMethodClass = aMethod.getDeclaringClass().getTheClass();
    Class categoryMethodClass = categoryMethod.getDeclaringClass().getTheClass();

    if (aMethodClass == categoryMethodClass) return Boolean.TRUE;
    boolean match = aMethodClass.isAssignableFrom(categoryMethodClass);
    if (match) return Boolean.TRUE;
    return null;
}
 
Example #13
Source File: ExpandoMetaClass.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Registers a new bean property
 *
 * @param property The property name
 * @param newValue The properties initial value
 */
public void registerBeanProperty(final String property, final Object newValue) {
    performOperationOnMetaClass(() -> {
        Class type = newValue == null ? Object.class : newValue.getClass();

        MetaBeanProperty mbp = newValue instanceof MetaBeanProperty ? (MetaBeanProperty) newValue : new ThreadManagedMetaBeanProperty(theClass, property, type, newValue);

        final MetaMethod getter = mbp.getGetter();
        final MethodKey getterKey = new DefaultCachedMethodKey(theClass, getter.getName(), CachedClass.EMPTY_ARRAY, false);
        final MetaMethod setter = mbp.getSetter();
        final MethodKey setterKey = new DefaultCachedMethodKey(theClass, setter.getName(), setter.getParameterTypes(), false);
        addMetaMethod(getter);
        addMetaMethod(setter);

        expandoMethods.put(setterKey, setter);
        expandoMethods.put(getterKey, getter);
        expandoProperties.put(mbp.getName(), mbp);

        addMetaBeanProperty(mbp);
        performRegistryCallbacks();
    });
}
 
Example #14
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
private MetaProperty getMetaProperty(Class _clazz, String name, boolean useSuper, boolean useStatic) {
    if (_clazz == theClass)
        return getMetaProperty(name, useStatic);

    CachedClass clazz = ReflectionCache.getCachedClass(_clazz);
    while (true) {
        SingleKeyHashMap propertyMap;
        if (useStatic) {
            propertyMap = staticPropertyIndex;
        } else if (useSuper) {
            propertyMap = classPropertyIndexForSuper.getNullable(clazz);
        } else {
            propertyMap = classPropertyIndex.getNullable(clazz);
        }
        if (propertyMap == null) {
            if (clazz != theCachedClass) {
                clazz = theCachedClass;
                continue;
            } else {
                return null;
            }
        }
        return (MetaProperty) propertyMap.get(name);
    }
}
 
Example #15
Source File: GroovyCategorySupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void applyUse(CachedClass cachedClass) {
    CachedMethod[] methods = cachedClass.getMethods();
    for (CachedMethod cachedMethod : methods) {
        if (cachedMethod.isStatic() && cachedMethod.isPublic()) {
            CachedClass[] paramTypes = cachedMethod.getParameterTypes();
            if (paramTypes.length > 0) {
                CachedClass metaClass = paramTypes[0];
                CategoryMethod mmethod = new CategoryMethod(cachedMethod, metaClass.getTheClass());
                final String name = cachedMethod.getName();
                CategoryMethodList list = get(name);
                if (list == null || list.level != level) {
                    list = new CategoryMethodList(name, level, list);
                    put(name, list);
                }
                list.add(mmethod);
                Collections.sort(list);
                cachePropertyAccessor(mmethod);
            }
        }
    }
}
 
Example #16
Source File: MetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected static boolean equal(CachedClass[] a, Class[] b) {
    if (a.length == b.length) {
        for (int i = 0, size = a.length; i < size; i++) {
            if (!a[i].getTheClass().equals(b[i])) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example #17
Source File: NewMetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
public NewMetaMethod(CachedMethod method) {
    super(method);
    bytecodeParameterTypes = method.getParameterTypes();

    int size = bytecodeParameterTypes.length;
    CachedClass[] logicalParameterTypes;
    if (size <= 1) {
        logicalParameterTypes = EMPTY_TYPE_ARRAY;
    } else {
        logicalParameterTypes = new CachedClass[--size];
        System.arraycopy(bytecodeParameterTypes, 1, logicalParameterTypes, 0, size);
    }
    setParametersTypes(logicalParameterTypes);
}
 
Example #18
Source File: CallSiteGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static Constructor compileStaticMethod(CachedMethod cachedMethod) {
    ClassWriter cw = makeClassWriter();

    final CachedClass declClass = cachedMethod.getDeclaringClass();
    final CallSiteClassLoader callSiteLoader = declClass.getCallSiteLoader();
    final String name = callSiteLoader.createClassName(cachedMethod.getName());

    final byte[] bytes = genStaticMetaMethodSite(cachedMethod, cw, name);

    return callSiteLoader.defineClassAndGetConstructor(name, bytes);
}
 
Example #19
Source File: MethodRankHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static String listParameterNames(CachedClass[] cachedClasses){
  StringBuilder sb = new StringBuilder();
  for(int i =0; i < cachedClasses.length;i++){
      if(i != 0) sb.append(", ");
      sb.append(cachedClasses[i].getName());
  }
  return sb.toString();
}
 
Example #20
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 5 votes vote down vote up
private MetaProperty getMetaProperty(String name, boolean useStatic) {
    CachedClass clazz = theCachedClass;
    SingleKeyHashMap propertyMap;
    if (useStatic) {
        propertyMap = staticPropertyIndex;
    } else {
        propertyMap = classPropertyIndex.getNullable(clazz);
    }
    if (propertyMap == null) {
        return null;
    }
    return (MetaProperty) propertyMap.get(name);
}
 
Example #21
Source File: MetaMethod.java    From groovy with Apache License 2.0 5 votes vote down vote up
public String getMopName() {
    if (mopName == null) {
      String name = getName();
      CachedClass declaringClass = getDeclaringClass();
      if (Modifier.isPrivate(getModifiers()))
        mopName = "this$" + declaringClass.getSuperClassDistance() + "$" + name;
      else 
        mopName = "super$" + declaringClass.getSuperClassDistance() + "$" + name;
    }
    return mopName;
}
 
Example #22
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected LinkedList<CachedClass> getSuperClasses() {
    LinkedList<CachedClass> superClasses = new LinkedList<>();

    if (theClass.isInterface()) {
        superClasses.addFirst(ReflectionCache.OBJECT_CLASS);
    } else {
        for (CachedClass c = theCachedClass; c != null; c = c.getCachedSuperClass()) {
            superClasses.addFirst(c);
        }
        if (theCachedClass.isArray && theClass != Object[].class && !theClass.getComponentType().isPrimitive()) {
            superClasses.addFirst(ReflectionCache.OBJECT_ARRAY_CLASS);
        }
    }
    return superClasses;
}
 
Example #23
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addInterfaceMethods(Set<CachedClass> interfaces) {
    MetaMethodIndex.Header header = metaMethodIndex.getHeader(theClass);
    for (CachedClass c : interfaces) {
        final CachedMethod[] m = c.getMethods();
        for (int i = 0; i != m.length; ++i) {
            MetaMethod method = m[i];
            addMetaMethodToIndex(method, header);
        }
    }
}
 
Example #24
Source File: MixinInstanceMetaProperty.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static MetaMethod createGetter(final MetaProperty property, final MixinInMetaClass mixinInMetaClass) {
    return new MetaMethod() {
        final String name = getGetterName(property.getName(), property.getType());
        {
            setParametersTypes (CachedClass.EMPTY_ARRAY);
        }

        public int getModifiers() {
            return Modifier.PUBLIC;
        }

        public String getName() {
            return name;
        }

        public Class getReturnType() {
            return property.getType();
        }

        public CachedClass getDeclaringClass() {
            return mixinInMetaClass.getInstanceClass();
        }

        public Object invoke(Object object, Object[] arguments) {
            return property.getProperty(mixinInMetaClass.getMixinInstance(object));
        }
    };
}
 
Example #25
Source File: MixinInstanceMetaProperty.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static MetaMethod createSetter(final MetaProperty property, final MixinInMetaClass mixinInMetaClass) {
  return new MetaMethod() {
      final String name = getSetterName(property.getName());
      {
          setParametersTypes (new CachedClass [] {ReflectionCache.getCachedClass(property.getType())} );
      }

      public int getModifiers() {
          return Modifier.PUBLIC;
      }

      public String getName() {
          return name;
      }

      public Class getReturnType() {
          return property.getType();
      }

      public CachedClass getDeclaringClass() {
          return mixinInMetaClass.getInstanceClass();
      }

      public Object invoke(Object object, Object[] arguments) {
          property.setProperty(mixinInMetaClass.getMixinInstance(object), arguments[0]);
          return null;
      }
  };
}
 
Example #26
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean isGenericGetMethod(MetaMethod method) {
    if (method.getName().equals("get")) {
        CachedClass[] parameterTypes = method.getParameterTypes();
        return parameterTypes.length == 1 && parameterTypes[0].getTheClass() == String.class;
    }
    return false;
}
 
Example #27
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * @see MetaObjectProtocol#getMetaProperty(String)
 */
public MetaProperty getMetaProperty(String name) {
    MetaProperty metaProperty = null;

    SingleKeyHashMap propertyMap = classPropertyIndex.getNotNull(theCachedClass);
    metaProperty = (MetaProperty) propertyMap.get(name);
    if (metaProperty == null) {
        metaProperty = (MetaProperty) staticPropertyIndex.get(name);
        if (metaProperty == null) {
            propertyMap = classPropertyIndexForSuper.getNotNull(theCachedClass);
            metaProperty = (MetaProperty) propertyMap.get(name);
            if (metaProperty == null) {
                CachedClass superClass = theCachedClass;
                while (superClass != null && superClass != ReflectionCache.OBJECT_CLASS) {
                    MetaBeanProperty property = findPropertyInClassHierarchy(name, superClass);
                    if (property != null) {
                        onSuperPropertyFoundInHierarchy(property);
                        metaProperty = property;
                        break;
                    }
                    superClass = superClass.getCachedSuperClass();
                }
            }
        }
    }

    return metaProperty;
}
 
Example #28
Source File: DgmConverter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected static void loadParameters(CachedMethod method, int argumentIndex, MethodVisitor mv) {
    CachedClass[] parameters = method.getParameterTypes();
    int size = parameters.length - 1;
    for (int i = 0; i < size; i++) {
        // unpack argument from Object[]
        mv.visitVarInsn(ALOAD, argumentIndex);
        BytecodeHelper.pushConstant(mv, i);
        mv.visitInsn(AALOAD);

        // cast argument to parameter class, inclusive unboxing
        // for methods with primitive types
        Class type = parameters[i + 1].getTheClass();
        BytecodeHelper.doCast(mv, type);
    }
}
 
Example #29
Source File: MetaClassRegistryImpl.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createMetaMethodFromClass(Map<CachedClass, List<MetaMethod>> map, Class aClass) {
    try {
        MetaMethod method = (MetaMethod) aClass.getDeclaredConstructor().newInstance();
        final CachedClass declClass = method.getDeclaringClass();
        List<MetaMethod> arr = map.computeIfAbsent(declClass, k -> new ArrayList<MetaMethod>(4));
        arr.add(method);
        instanceMethods.add(method);
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { /* ignore */
    }
}
 
Example #30
Source File: ExpandoMetaClass.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the name of the method specified and the number of arguments make it a javabean property
 *
 * @param name True if its a Javabean property
 * @param args The arguments
 * @return True if it is a javabean property method
 */
private boolean isGetter(String name, CachedClass[] args) {
    if (name == null || name.length() == 0 || args == null) return false;
    if (args.length != 0) return false;

    if (name.startsWith("get")) {
        name = name.substring(3);
        return isPropertyName(name);
    }
    if (name.startsWith("is")) {
        name = name.substring(2);
        return isPropertyName(name);
    }
    return false;
}