Example usage for java.lang.reflect Type equals

List of usage examples for java.lang.reflect Type equals

Introduction

In this page you can find the example usage for java.lang.reflect Type equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Indicates whether some other object is "equal to" this one.

Usage

From source file:com.fitbur.jestify.junit.spring.injector.NameMockInjector.java

@Override
public void inject() {
    Map<DescriptorKey, ParameterDescriptor> parameterDescriptors = context.getParamaterDescriptors();
    Field field = fieldDescriptor.getField();
    Type fieldType = field.getGenericType();

    Mock mock = fieldDescriptor.getMock().get();
    String mockName = mock.name();
    DescriptorKey descriptorKey = new DescriptorKey(fieldType, mockName);

    ParameterDescriptor parameterDescriptor = parameterDescriptors.get(descriptorKey);

    checkArgument(parameterDescriptor != null,
            "Can not mock field '%s'. Could not find class under test constructor "
                    + "argument with the name '%s'.",
            field.getName(), mockName);// w  ww  . j av  a2s.c  om

    Parameter parameter = parameterDescriptor.getParameter();
    Integer index = parameterDescriptor.getIndex();
    Type parameterType = parameter.getParameterizedType();

    checkArgument(fieldType.equals(parameterType),
            "Can not mock field '%s'. Test class field type '%s' and class under test "
                    + "constructor parameter type '%s' with name '%s' do not match.",
            field.getName(), field.getGenericType(), parameterType, mockName);

    ResolvableType resolver = ResolvableType.forType(parameterType);

    Class rawType;

    if (resolver.hasGenerics()) {
        if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
            rawType = resolver.getRawClass();
        } else {
            rawType = resolver.resolve();
        }
    } else {
        rawType = (Class) parameterType;
    }

    checkArgument(arguments[index] == null,
            "Can not mock field '%s'. Multipe test class fields have the same index of '%d'", field.getName(),
            index);

    Object instance = testReifier.reifyField(fieldDescriptor, parameterDescriptor);

    arguments[index] = instance;
}

From source file:net.firejack.platform.core.utils.Factory.java

public Class getGenericParameterClass(Class actualClass, Class genericClass, int parameterIndex) {
    if (!genericClass.isAssignableFrom(actualClass) || genericClass.equals(actualClass)) {
        throw new IllegalArgumentException(
                "Class " + genericClass.getName() + " is not a superclass of " + actualClass.getName() + ".");
    }//from ww  w.j av  a 2 s .  c om

    Stack<ParameterizedType> types = new Stack<ParameterizedType>();

    Class clazz = actualClass;

    while (true) {
        Type currentType = genericClass.isInterface() ? getGenericInterface(clazz, genericClass)
                : clazz.getGenericSuperclass();

        Type rawType;
        if (currentType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) currentType;
            types.push(type);
            rawType = type.getRawType();
        } else {
            types.clear();
            rawType = currentType;
        }

        if (!rawType.equals(genericClass)) {
            clazz = (Class) rawType;
        } else {
            break;
        }
    }

    if (types.isEmpty()) {
        return (Class) genericClass.getTypeParameters()[parameterIndex].getGenericDeclaration();
    }

    Type result = types.pop().getActualTypeArguments()[parameterIndex];

    while (result instanceof TypeVariable && !types.empty()) {
        int actualArgumentIndex = getParameterTypeDeclarationIndex((TypeVariable) result);
        ParameterizedType type = types.pop();
        result = type.getActualTypeArguments()[actualArgumentIndex];
    }

    if (result instanceof TypeVariable) {
        throw new IllegalStateException("Unable to resolve type variable " + result + "."
                + " Try to replace instances of parametrized class with its non-parameterized subtype.");
    }

    if (result instanceof ParameterizedType) {
        result = ((ParameterizedType) result).getRawType();
    }

    if (result == null) {
        throw new IllegalStateException(
                "Unable to determine actual parameter type for " + actualClass.getName() + ".");
    }

    if (!(result instanceof Class)) {
        throw new IllegalStateException(
                "Actual parameter type for " + actualClass.getName() + " is not a Class.");
    }

    return (Class) result;
}

From source file:richtercloud.reflection.form.builder.jpa.fieldhandler.JPAMappingFieldHandler.java

@Override
protected Pair<JComponent, ComponentHandler<?>> handle0(Field field, Object instance,
        final FieldUpdateListener updateListener, JPAReflectionFormBuilder reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    if (field == null) {
        throw new IllegalArgumentException("fieldClass mustn't be null");
    }/*from  ww w  .  j  a  v  a 2 s .  c om*/
    Type fieldType = field.getGenericType();
    Object fieldValue = field.get(instance);
    String fieldName = field.getName();
    Class<?> fieldDeclaringClass = field.getDeclaringClass();
    if (field.getAnnotation(Id.class) != null) {
        if (!(fieldType instanceof Class)) {
            throw new IllegalArgumentException("@Id annotated field has to be a class");
        }
        Class<?> fieldTypeClass = (Class<?>) fieldType;
        if (fieldTypeClass.equals(Long.class)) {
            Long fieldValueCast = (Long) field.get(instance);
            NumberPanel<Long> retValue;
            if (fieldType.equals(Long.class)) {
                retValue = new LongIdPanel(this.idGenerator, instance, fieldValueCast, //initialValue
                        messageHandler, fieldRetriever);
            } else {
                throw new IllegalArgumentException(
                        String.format("field type %s is not supported", fieldValue.getClass()));
            }
            retValue.addUpdateListener(new NumberPanelUpdateListener<Long>() {

                @Override
                public void onUpdate(NumberPanelUpdateEvent<Long> event) {
                    updateListener.onUpdate(new FieldUpdateEvent<>(event.getNewValue()));
                }
            });
            return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue,
                    LONG_ID_PANEL_COMPONENT_RESETTER);
        } else {
            throw new IllegalArgumentException(
                    String.format("@Id annotated field type %s not supported", field.getGenericType()));
        }
    }
    if (field.getAnnotation(ElementCollection.class) != null) {
        //can't be handled differently because otherwise a QueryPanel would
        //be tried to be used and IllegalArgumentException thrown at
        //initialization
        if (fieldValue != null && !(fieldValue instanceof List)) {
            throw new IllegalArgumentException("field values isn't an instance of List");
        }
        Pair<JComponent, ComponentHandler<?>> retValue = this.elementCollectionTypeHandler.handle(
                field.getGenericType(), (List<Object>) fieldValue, fieldName, fieldDeclaringClass,
                updateListener, reflectionFormBuilder);
        return retValue;
    }
    if (field.getAnnotation(OneToMany.class) != null || field.getAnnotation(ManyToMany.class) != null) {
        Pair<JComponent, ComponentHandler<?>> retValue = this.toManyTypeHandler.handle(field.getGenericType(),
                (List<Object>) fieldValue, fieldName, fieldDeclaringClass, updateListener,
                reflectionFormBuilder);
        return retValue;
    }
    if (field.getAnnotation(OneToOne.class) != null || field.getAnnotation(ManyToOne.class) != null) {
        Pair<JComponent, ComponentHandler<?>> retValue = this.toOneTypeHandler.handle(field.getGenericType(),
                fieldValue, fieldName, fieldDeclaringClass, updateListener, reflectionFormBuilder);
        return retValue;
    }
    if (field.getType() instanceof Class) {
        Class<?> fieldTypeClass = field.getType();
        if (fieldTypeClass.getAnnotation(Embeddable.class) != null) {
            FieldHandler fieldHandler = embeddableMapping.get(fieldType);
            JComponent retValue = fieldHandler.handle(field, instance, updateListener, reflectionFormBuilder);
            return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, fieldHandler);
        }
    }
    return super.handle0(field, instance, updateListener, reflectionFormBuilder);
}

From source file:com.fitbur.jestify.junit.spring.injector.TypeMockInjector.java

@Override
public void inject() {
    Map<DescriptorKey, ParameterDescriptor> parameterDescriptors = context.getParamaterDescriptors();
    Field field = fieldDescriptor.getField();

    Mock mock = fieldDescriptor.getMock().get();
    Type fieldType = field.getGenericType();
    String fieldName = field.getName();
    DescriptorKey descriptorKey = new DescriptorKey(fieldType, fieldName);

    //if there is a parameter descriptor that matches the field then lets use that
    if (parameterDescriptors.containsKey(descriptorKey)) {
        ParameterDescriptor descriptor = parameterDescriptors.get(descriptorKey);
        Parameter parameter = descriptor.getParameter();
        Integer index = descriptor.getIndex();
        ResolvableType resolver = ResolvableType.forType(fieldType);

        Class rawType;//from   w  ww  .j a  v a 2 s  .  c om

        if (resolver.hasGenerics()) {
            if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
                rawType = resolver.getRawClass();
            } else {
                rawType = resolver.resolve();
            }
        } else {
            rawType = (Class) fieldType;
        }
        Object instance = testReifier.reifyField(fieldDescriptor, descriptor);
        arguments[index] = instance;
    } else {
        //otherwise find the right parameter based on the type of the field
        Collection<ParameterDescriptor> descriptors = parameterDescriptors.values();
        for (ParameterDescriptor descriptor : descriptors) {
            Parameter parameter = descriptor.getParameter();
            Type parameterType = parameter.getParameterizedType();
            Integer index = descriptor.getIndex();

            ResolvableType resolver = ResolvableType.forType(parameterType);

            Class rawType;

            if (resolver.hasGenerics()) {
                if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
                    rawType = resolver.getRawClass();
                } else {
                    rawType = resolver.resolve();
                }
            } else {
                rawType = resolver.resolve();
            }

            if (arguments[index] != null) {
                continue;
            }

            if (parameterType.equals(fieldType)) {
                Object instance = testReifier.reifyField(fieldDescriptor, descriptor);
                arguments[index] = instance;
                break;
            }

        }
    }

}

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

/**
 * Based on most recent test execution, update the mocking configuration.
 * After calling this method, it is <b>necessary</b> to provide the missing
 * VariableReferences, if any, using addMissingInputs.
 *
 * @return a ordered, non-null list of types of missing new inputs that will need to be provided
 *
 *//*  w ww . j a va  2 s.  c o m*/
public List<Type> updateMockedMethods() throws ConstructionFailedException {

    logger.debug("Executing updateMockedMethods. Parameter size: " + parameters.size());

    List<Type> list = new ArrayList<>();

    assert !super.parameters.contains(null);
    assert mockedMethods.size() == methodParameters.size();

    List<VariableReference> copy = new ArrayList<>(super.parameters);
    assert copy.size() == super.parameters.size();

    super.parameters.clear();
    mockedMethods.clear(); //important to remove all the no longer used calls

    Map<String, int[]> mpCopy = new LinkedHashMap<>();

    List<MethodDescriptor> executed = listener.getCopyOfMethodDescriptors();

    int mdIndex = 0;

    for (MethodDescriptor md : executed) {
        mockedMethods.add(md);

        if (!md.shouldBeMocked() || md.getCounter() == 0) {
            //void method or not called, so no parameter needed for it
            mpCopy.put(md.getID(), null);
            continue;
        }

        int added = 0;

        logger.debug("Method called on mock object: " + md.getMethod());

        //infer parameter mapping of current vars from previous execution, if any
        int[] minMax = methodParameters.get(md.getID());
        int existingParameters; //total number of existing parameters
        if (minMax == null) {
            //before it was not called
            minMax = new int[] { -1, -1 };
            existingParameters = 0;
        } else {
            assert minMax[1] >= minMax[0] && minMax[0] >= 0;
            assert minMax[1] < copy.size() : "Max=" + minMax[1] + " but n=" + copy.size();
            existingParameters = 1 + (minMax[1] - minMax[0]);
        }

        assert existingParameters <= Properties.FUNCTIONAL_MOCKING_INPUT_LIMIT;

        //check if less calls
        if (existingParameters > md.getCounter()) {
            //now the method has been called less times,
            //so remove the last calls, ie decrease counter
            minMax[1] -= (existingParameters - md.getCounter());
        }

        if (existingParameters > 0) {
            for (int i = minMax[0]; i <= minMax[1]; i++) {
                //align super class data structure
                super.parameters.add(copy.get(i));
                added++;
            }
        }

        //check if rather more calls
        if (existingParameters < md.getCounter()) {
            for (int i = existingParameters; i < md.getCounter()
                    && i < Properties.FUNCTIONAL_MOCKING_INPUT_LIMIT; i++) {
                // Create a copy as the typemap is stored in the class during generic instantiation
                // but we might want to have a different type for each call of the same method invocation
                GenericClass calleeClass = new GenericClass(retval.getGenericClass());
                Type returnType = md.getGenericMethodFor(calleeClass).getGeneratedType();
                assert !returnType.equals(Void.TYPE);
                logger.debug("Return type: " + returnType + " for retval " + retval.getGenericClass());
                list.add(returnType);

                super.parameters.add(null); //important place holder for following updates
                added++;
            }
        }

        minMax[0] = mdIndex;
        minMax[1] = (mdIndex + added - 1); //max is inclusive
        assert minMax[1] >= minMax[0] && minMax[0] >= 0; //max >= min
        assert super.parameters.size() == minMax[1] + 1;

        mpCopy.put(md.getID(), minMax);
        mdIndex += added;
    }

    methodParameters.clear();
    methodParameters.putAll(mpCopy);
    for (MethodDescriptor md : mockedMethods) {
        if (!methodParameters.containsKey(md.getID())) {
            methodParameters.put(md.getID(), null);
        }
    }

    return list;
}

From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java

private static MethodDescriptor describMethodIfMatching(Method method, Type[] requiredTypes, Type[] exactTypes,
        Type[] optionalTypes, Type returnType) {
    Type[] argTypes = method.getGenericParameterTypes();
    if (argTypes.length > (requiredTypes.length + exactTypes.length + optionalTypes.length)) {
        return null;
    }/*from   w  w  w  .ja  va2s.c  o m*/

    int[] argIndexs = new int[argTypes.length];
    int[] argMatchingRates = new int[argTypes.length];
    for (int i = 0; i < argIndexs.length; i++) {
        argIndexs[i] = -1;
        argMatchingRates[i] = 0;
    }

    Type[] requiredTypeArray = new Type[requiredTypes.length];
    Type[] exactTypeArray = new Type[exactTypes.length];
    Type[] optionalTypeArray = new Type[optionalTypes.length];
    System.arraycopy(requiredTypes, 0, requiredTypeArray, 0, requiredTypes.length);
    System.arraycopy(exactTypes, 0, exactTypeArray, 0, exactTypes.length);
    System.arraycopy(optionalTypes, 0, optionalTypeArray, 0, optionalTypes.length);

    // 
    if (returnType != null && !returnType.equals(IgnoreType.class)) {
        Type methodReturnType = method.getGenericReturnType();
        if (isTypeAssignableFrom(returnType, methodReturnType) == 0) {
            methodReturnType = toNonPrimitiveClass(methodReturnType);
            if (isTypeAssignableFrom(returnType, methodReturnType) == 0) {
                return null;
            }
        }
    }

    // ?
    for (int i = 0; i < requiredTypeArray.length; i++) {
        Type requiredType = requiredTypeArray[i];
        int matchingArg = -1;
        for (int j = 0; j < argTypes.length; j++) {
            Type argType = argTypes[j];
            if (isTypeAssignableFrom(argType, requiredType) > 0) {
                if (matchingArg == -1) {
                    matchingArg = j;
                } else {
                    Type conflictType = argTypes[matchingArg];
                    if (argType.equals(conflictType)) {
                        // ????
                        return null;
                    } else if (isTypeAssignableFrom(conflictType, argType) > 0) {
                        matchingArg = j;
                    }
                }
            }
        }

        // ?
        if (matchingArg != -1) {
            argIndexs[matchingArg] = i;
            argMatchingRates[matchingArg] = 10;
        } else {
            return null;
        }
    }

    // ??
    for (int i = 0; i < exactTypeArray.length; i++) {
        Type exactType = exactTypeArray[i];
        int matchingArg = -1;
        for (int j = 0; j < argTypes.length; j++) {
            Type argType = argTypes[j];
            if (isTypeAssignableFrom(exactType, argType) > 0) {
                if (matchingArg == -1) {
                    matchingArg = j;
                } else {
                    // ?????
                    return null;
                }
            }
        }

        // ??
        if (matchingArg != -1) {
            if (argMatchingRates[matchingArg] == 0) {
                argIndexs[matchingArg] = requiredTypeArray.length + i;
                argMatchingRates[matchingArg] = 9;
            } else {
                // ?????
                return null;
            }
        }
    }

    // ???
    int conflictArg = -1, matchingRate = 1000;
    for (int i = 0; i < argTypes.length; i++) {
        if (argMatchingRates[i] == 0) {
            Type argType = argTypes[i];
            for (int j = 0; j < optionalTypeArray.length; j++) {
                Type optionalType = optionalTypeArray[j];
                if (optionalType != null) {
                    int rate = isTypeAssignableFrom(argType, optionalType);
                    if (rate == 0) {
                        rate = isTypesCompatible(argType, optionalType);
                    }
                    if (rate > 0) {
                        int originMatchingRate = argMatchingRates[i];
                        if (originMatchingRate == 0) {
                            argIndexs[i] = requiredTypeArray.length + exactTypeArray.length + j;
                            argMatchingRates[i] = rate;
                            matchingRate += (rate * 2);
                        } else if (conflictArg != -1) {
                            // ????
                            return null;
                        } else if (originMatchingRate > rate) {
                            matchingRate -= (5 - (originMatchingRate - rate)); // 
                        } else if (rate > originMatchingRate) {
                            argIndexs[i] = requiredTypeArray.length + exactTypeArray.length + j;
                            argMatchingRates[i] = rate;
                            matchingRate -= (5 - (rate - originMatchingRate)); // 
                        } else {
                            // ????
                            argIndexs[i] = -1;
                            conflictArg = i;
                            matchingRate -= (argTypes.length * 10);
                        }
                    }
                }
            }

            if (argIndexs[i] != -1) {
                optionalTypeArray[argIndexs[i] - exactTypeArray.length - requiredTypeArray.length] = null;
            }
        }
    }

    // ????
    if (conflictArg != -1) {
        Type argType = argTypes[conflictArg];
        for (int i = 0; i < optionalTypeArray.length; i++) {
            Type optionalType = optionalTypeArray[i];
            if (optionalType != null && isTypeAssignableFrom(argType, optionalType) > 0) {
                if (argIndexs[conflictArg] == -1) {
                    argIndexs[conflictArg] = requiredTypeArray.length + i;
                } else {
                    return null;
                }
            }
        }
    }

    int undetermine = 0, undetermineIndex = -1;
    for (int i = 0; i < argIndexs.length; i++) {
        if (argIndexs[i] == -1) {
            undetermine++;
            undetermineIndex = i;
        }
    }

    // ??????
    if (undetermine == 1 && optionalTypes.length == 1) {
        Type argType = argTypes[undetermineIndex];
        if (isSimpleType(argType) && isSimpleType(optionalTypes[0])) {
            argIndexs[undetermineIndex] = requiredTypeArray.length + exactTypeArray.length;
            undetermine = 0;
            matchingRate -= 200;
        }
    }

    if (undetermine > 0) {
        return null;
    }
    return new MethodDescriptor(method, argIndexs, matchingRate);
}

From source file:org.xwiki.extension.jar.JarExtensionHandlerTest.java

private void assertNotEquals(Type type1, Type type2) {
    if (type1.equals(type2)) {
        Assert.fail("expected not equals");
    }//from   w  w  w  .  ja va2  s .c  om
}

From source file:org.xwiki.extension.jar.JarExtensionHandlerTest.java

/**
 * Check that an extension is effectively available in the given namespace and that the corresponding component
 * manager provide the expected default implementation.
 *
 * @param role the role expected to be provided by the extension
 * @param implementation the implementation expected for the given role
 * @param namespace the namespace where the extension is expected to installed
 * @param <T> the role class//from   w  ww .j a  v a2s . c om
 * @return the effective role class in the extension class loader
 * @throws Exception on error
 */
private <T> Type checkJarExtensionAvailability(Type role, Class<? extends T> implementation, String namespace)
        throws Exception {
    ClassLoader extensionLoader = getExtensionClassloader(namespace);
    Assert.assertNotNull(extensionLoader);
    Assert.assertNotSame(this.testApplicationClassloader, extensionLoader);

    Type loadedRole = getLoadedType(role, extensionLoader);
    // Ensure the loaded role does not came from the application classloader (a check to validate the test)
    Assert.assertFalse(loadedRole.equals(role));

    if (namespace != null) {
        try {
            this.jarExtensionClassLoader.getURLClassLoader(null, false)
                    .loadClass(ReflectionUtils.getTypeClass(loadedRole).getName());
            Assert.fail("the interface should not be in the root class loader");
        } catch (ClassNotFoundException expected) {
            // expected
        }
    }

    // check components managers
    Class<?> componentInstanceClass = null;
    if (namespace != null) {
        componentInstanceClass = getExtensionComponentManager(namespace).getInstance(loadedRole).getClass();

        try {
            this.mocker.getInstance(loadedRole);
            Assert.fail("the component should not be in the root component manager");
        } catch (ComponentLookupException expected) {
            // expected
        }
    } else {
        componentInstanceClass = this.mocker.getInstance(loadedRole).getClass();
    }
    Assert.assertEquals(implementation.getName(), componentInstanceClass.getName());
    Assert.assertNotSame(implementation, componentInstanceClass);

    return loadedRole;
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

private boolean isMap(Type claz) {
    return (claz.equals(Map.class) || claz.equals(HashMap.class) || claz.equals(LinkedHashMap.class)
            || claz.equals(TreeMap.class));
}