Java Code Examples for org.codehaus.groovy.reflection.CachedClass

The following examples show how to use org.codehaus.groovy.reflection.CachedClass. These examples are extracted from open source projects. 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 Project: groovy   Source File: GroovyCategorySupport.java    License: 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 2
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 3
Source Project: groovy   Source File: MetaClassHelper.java    License: 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 4
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 5
Source Project: groovy   Source File: MetaMethodIndex.java    License: 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 6
Source Project: groovy   Source File: MetaClassRegistryImpl.java    License: 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 7
Source Project: groovy   Source File: Java9.java    License: 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 8
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 9
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 10
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 11
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 12
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 13
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 14
Source Project: groovy   Source File: ExpandoMetaClass.java    License: 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 15
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 16
Source Project: groovy   Source File: GroovyCategorySupport.java    License: Apache License 2.0 5 votes vote down vote up
private void use(Class categoryClass) {
    CachedClass cachedClass = ReflectionCache.getCachedClass(categoryClass);
    LinkedList<CachedClass> classStack = new LinkedList<CachedClass>();
    for (CachedClass superClass = cachedClass; superClass.getTheClass()!=Object.class; superClass = superClass.getCachedSuperClass()) {
        classStack.add(superClass);
    }

    while (!classStack.isEmpty()) {
        CachedClass klazz = classStack.removeLast();
        applyUse(klazz);
    }
}
 
Example 17
Source Project: groovy   Source File: AbstractCallSite.java    License: Apache License 2.0 5 votes vote down vote up
static boolean noCoerce(final ParameterTypes metaMethod, final Object[] args) {
    final CachedClass[] paramClasses = metaMethod.getParameterTypes();
    if (paramClasses.length != args.length)
        return false;

    for (int i = 0; i < paramClasses.length; i++) {
        CachedClass paramClass = paramClasses[i];
        if (args[i] != null && !paramClass.isDirectlyAssignable(args[i]))
            return true;
    }
    return false;
}
 
Example 18
Source Project: groovy   Source File: CallSiteGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static Constructor compilePojoMethod(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 = genPojoMetaMethodSite(cachedMethod, cw, name);

    return callSiteLoader.defineClassAndGetConstructor(name, bytes);
}
 
Example 19
Source Project: groovy   Source File: CallSiteGenerator.java    License: 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 20
Source Project: groovy   Source File: MethodRankHelper.java    License: 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 21
Source Project: groovy   Source File: MetaMethod.java    License: 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 22
Source Project: groovy   Source File: MetaClassImpl.java    License: Apache License 2.0 5 votes vote down vote up
protected static String createErrorMessageForAmbiguity(String theClassName, String name, Class[] arguments, LinkedList matches) {
    StringBuilder msg = new StringBuilder("Ambiguous method overloading for method ");
    msg.append(theClassName).append("#").append(name)
            .append(".\nCannot resolve which method to invoke for ")
            .append(InvokerHelper.toString(arguments))
            .append(" due to overlapping prototypes between:");
    for (final Object match : matches) {
        CachedClass[] types = ((ParameterTypes) match).getParameterTypes();
        msg.append("\n\t").append(InvokerHelper.toString(types));
    }
    return msg.toString();
}
 
Example 23
Source Project: groovy   Source File: MetaClassImpl.java    License: Apache License 2.0 5 votes vote down vote up
public SingleKeyHashMap getNotNull(CachedClass key) {
    Entry res = getOrPut(key);
    if (res.value == null) {
        res.value = new SingleKeyHashMap();
    }
    return (SingleKeyHashMap) res.value;
}
 
Example 24
Source Project: groovy   Source File: MetaClassImpl.java    License: 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 25
Source Project: groovy   Source File: NewMetaMethod.java    License: 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 26
Source Project: groovy   Source File: MixinInstanceMetaProperty.java    License: 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 27
Source Project: groovy   Source File: MixinInstanceMetaProperty.java    License: 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 28
Source Project: groovy   Source File: MetaMethod.java    License: 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 29
Source Project: groovy   Source File: MetaClassRegistryImpl.java    License: 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 Project: groovy   Source File: ExpandoMetaClass.java    License: 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;
}