Example usage for java.util Collection getClass

List of usage examples for java.util Collection getClass

Introduction

In this page you can find the example usage for java.util Collection getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

@SuppressWarnings("unchecked")
private Collection convertToTypedCollection(Collection original, String propertyName, Class requiredType,
        TypeDescriptor typeDescriptor) {

    if (!Collection.class.isAssignableFrom(requiredType)) {
        return original;
    }//from w w  w  .  j a  va2s  .  c  om

    boolean approximable = CollectionFactory.isApproximableCollectionType(requiredType);
    if (!approximable && !canCreateCopy(requiredType)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Custom Collection type [" + original.getClass().getName()
                    + "] does not allow for creating a copy - injecting original Collection as-is");
        }
        return original;
    }

    boolean originalAllowed = requiredType.isInstance(original);
    typeDescriptor = typeDescriptor.narrow(original);
    TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
    if (elementType == null && originalAllowed
            && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Iterator it;
    try {
        it = original.iterator();
        if (it == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Collection of type [" + original.getClass().getName()
                        + "] returned null Iterator - injecting original Collection as-is");
            }
            return original;
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Collection of type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is: " + ex);
        }
        return original;
    }

    Collection convertedCopy;
    try {
        if (approximable) {
            convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
        } else {
            convertedCopy = (Collection) requiredType.newInstance();
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot create copy of Collection type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is: " + ex);
        }
        return original;
    }

    int i = 0;
    for (; it.hasNext(); i++) {
        Object element = it.next();
        String indexedPropertyName = buildIndexedPropertyName(propertyName, i);
        Object convertedElement = convertIfNecessary(indexedPropertyName, null, element,
                (elementType != null ? elementType.getType() : null), elementType);
        try {
            convertedCopy.add(convertedElement);
        } catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Collection type [" + original.getClass().getName()
                        + "] seems to be read-only - injecting original Collection as-is: " + ex);
            }
            return original;
        }
        originalAllowed = originalAllowed && (element == convertedElement);
    }
    return (originalAllowed ? original : convertedCopy);
}

From source file:org.springframework.beans.TypeConverterDelegate.java

@SuppressWarnings("unchecked")
private Collection<?> convertToTypedCollection(Collection<?> original, @Nullable String propertyName,
        Class<?> requiredType, @Nullable TypeDescriptor typeDescriptor) {

    if (!Collection.class.isAssignableFrom(requiredType)) {
        return original;
    }// ww  w.ja  va2  s  .com

    boolean approximable = CollectionFactory.isApproximableCollectionType(requiredType);
    if (!approximable && !canCreateCopy(requiredType)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Custom Collection type [" + original.getClass().getName()
                    + "] does not allow for creating a copy - injecting original Collection as-is");
        }
        return original;
    }

    boolean originalAllowed = requiredType.isInstance(original);
    TypeDescriptor elementType = (typeDescriptor != null ? typeDescriptor.getElementTypeDescriptor() : null);
    if (elementType == null && originalAllowed
            && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Iterator<?> it;
    try {
        it = original.iterator();
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Collection of type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is: " + ex);
        }
        return original;
    }

    Collection<Object> convertedCopy;
    try {
        if (approximable) {
            convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
        } else {
            convertedCopy = (Collection<Object>) ReflectionUtils.accessibleConstructor(requiredType)
                    .newInstance();
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot create copy of Collection type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is: " + ex);
        }
        return original;
    }

    int i = 0;
    for (; it.hasNext(); i++) {
        Object element = it.next();
        String indexedPropertyName = buildIndexedPropertyName(propertyName, i);
        Object convertedElement = convertIfNecessary(indexedPropertyName, null, element,
                (elementType != null ? elementType.getType() : null), elementType);
        try {
            convertedCopy.add(convertedElement);
        } catch (Throwable ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Collection type [" + original.getClass().getName()
                        + "] seems to be read-only - injecting original Collection as-is: " + ex);
            }
            return original;
        }
        originalAllowed = originalAllowed && (element == convertedElement);
    }
    return (originalAllowed ? original : convertedCopy);
}

From source file:com.haulmont.cuba.core.app.importexport.EntityImportExport.java

protected void importManyToManyCollectionAttribute(Entity srcEntity, Entity dstEntity, boolean createOp,
        EntityImportViewProperty importViewProperty, View regularView, CommitContext commitContext,
        Collection<ReferenceInfo> referenceInfoList) {
    Collection<Entity> srcPropertyValue = srcEntity.getValue(importViewProperty.getName());
    Collection<Entity> dstPropertyValue = dstEntity.getValue(importViewProperty.getName());
    if (dstPropertyValue == null)
        dstPropertyValue = new ArrayList<>();
    if (importViewProperty.getView() != null) {
        //create/update passed entities
        Collection<Entity> collection;
        try {//from  w w w  .j  a va 2s .  c o  m
            collection = srcPropertyValue.getClass().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Error on import entities", e);
        }

        for (Entity srcChildEntity : srcPropertyValue) {
            //create new referenced entity
            Entity dstChildEntity = null;
            for (Entity _entity : dstPropertyValue) {
                if (_entity.equals(srcChildEntity)) {
                    dstChildEntity = _entity;
                    break;
                }
            }
            dstChildEntity = importEntity(srcChildEntity, dstChildEntity, importViewProperty.getView(),
                    regularView, commitContext, referenceInfoList);
            collection.add(dstChildEntity);
        }

        if (importViewProperty.getCollectionImportPolicy() == CollectionImportPolicy.KEEP_ABSENT_ITEMS) {
            Collection<Entity> existingCollectionValue = dstEntity.getValue(importViewProperty.getName());
            if (existingCollectionValue != null) {
                for (Entity existingCollectionItem : existingCollectionValue) {
                    if (!collection.contains(existingCollectionItem))
                        collection.add(existingCollectionItem);
                }
            }
        }

        dstEntity.setValue(importViewProperty.getName(), collection);
    } else {
        //create ReferenceInfo objects - they will be parsed later
        Collection<Entity> existingCollectionValue = dstEntity.getValue(importViewProperty.getName());
        ReferenceInfo referenceInfo = new ReferenceInfo(dstEntity, createOp, importViewProperty,
                srcPropertyValue, existingCollectionValue);
        referenceInfoList.add(referenceInfo);
    }
}

From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java

protected Collection convertToTypedCollection(Collection original, String propertyName,
        MethodParameter methodParam) {/*from  w w  w .j  a  v  a 2s.c o m*/

    Class elementType = null;
    if (methodParam != null && JdkVersion.isAtLeastJava15()) {
        elementType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam);
    }
    if (elementType == null && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
        return original;
    }

    Collection convertedCopy = null;
    Iterator it = null;
    try {
        it = original.iterator();
        if (it == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Collection of type [" + original.getClass().getName()
                        + "] returned null Iterator - injecting original Collection as-is");
            }
            return original;
        }
        convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cannot access Collection of type [" + original.getClass().getName()
                    + "] - injecting original Collection as-is", ex);
        }
        return original;
    }
    boolean actuallyConverted = false;
    int i = 0;
    for (; it.hasNext(); i++) {
        Object element = it.next();
        String indexedPropertyName = buildIndexedPropertyName(propertyName, i);
        if (methodParam != null) {
            methodParam.increaseNestingLevel();
        }
        Object convertedElement = convertIfNecessary(indexedPropertyName, null, element, elementType, null,
                methodParam);
        if (methodParam != null) {
            methodParam.decreaseNestingLevel();
        }
        convertedCopy.add(convertedElement);
        actuallyConverted = actuallyConverted || (element != convertedElement);
    }
    return (actuallyConverted ? convertedCopy : original);
}

From source file:omero.util.IceMapper.java

/**
 * Copied from {@link ModelMapper#findCollection(Collection)} This could be
 * unified in that a method findCollection(Collection, Map) was added with
 * {@link ModelMapper} calling findCollection(source,model2target) and
 * {@link #reverseCollection(Collection)} calling
 * findCollection(source,target2model)./*from   w ww.  j  av  a  2s  .  c  om*/
 * 
 * @param collection
 * @return
 */
public Collection reverse(Collection source) { // FIXME throws
    // omero.ApiUsageException {
    return reverse(source, source == null ? null : source.getClass());
}

From source file:org.evosuite.utils.TestGenericClass.java

@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
@Test//from   ww  w.java  2  s  .c  om
public void test01() throws Throwable {

    /*
     * This test case come from compilation issue found during SBST'13 competition:
     * 
     * String string0 = vM0.run(vM0.stack);
     * 
     * SUT at:  http://www.massapi.com/source/jabref-2.6/src/java/net/sf/jabref/bst/VM.java.html
     * 
     * Snippet of interest:
     * 
     * 1) Stack<Object> stack = new Stack<Object>();
     * 2)  public String run(Collection<BibtexEntry> bibtex) {
     */

    Collection<?> col0 = new Stack<Object>();
    Collection<A> col1 = new Stack();
    Collection col2 = new Stack();
    Collection col3 = new Stack<Object>();

    /*
     *  following does not compile
     *  
     *  Collection<A> col = new Stack<Object>();
     *  
     *  but it can be generated by EvoSuite
     */

    GenericClass stack = new GenericClass(Stack.class).getWithWildcardTypes();
    GenericClass collection = new GenericClass(Collection.class).getWithWildcardTypes();
    Assert.assertTrue(stack.isAssignableTo(collection));

    GenericClass objectStack = new GenericClass(col0.getClass());
    Assert.assertTrue(objectStack.isAssignableTo(collection));

    Type typeColA = new TypeToken<Collection<A>>() {
    }.getType();
    Type typeStack = new TypeToken<Stack>() {
    }.getType();
    Type typeObjectStack = new TypeToken<Stack<Object>>() {
    }.getType();

    GenericClass classColA = new GenericClass(typeColA);
    GenericClass classStack = new GenericClass(typeStack).getWithWildcardTypes();
    GenericClass classObjectStack = new GenericClass(typeObjectStack);

    Assert.assertFalse(classStack.isAssignableTo(classColA));
    Assert.assertFalse(classObjectStack.isAssignableTo(classColA));
    Assert.assertFalse(classColA.isAssignableFrom(classObjectStack));
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

@SuppressWarnings("unchecked")
private void bindCollectionAssociation(MutablePropertyValues mpvs, PropertyValue pv) {
    Object v = pv.getValue();/*from   w  ww . j ava  2s  .  com*/
    final boolean isArray = v != null && v.getClass().isArray();

    if (!isArray && !(v instanceof String))
        return;

    Collection collection = (Collection) bean.getPropertyValue(pv.getName());
    collection.clear();
    final Class associatedType = getReferencedTypeForCollection(pv.getName(), getTarget());
    final PropertyEditor propertyEditor = findCustomEditor(collection.getClass(), pv.getName());
    if (propertyEditor == null) {
        if (isDomainAssociation(associatedType)) {
            if (isArray) {
                Object[] identifiers = (Object[]) v;
                for (Object id : identifiers) {
                    if (id != null) {
                        associateObjectForId(pv, id, associatedType);
                    }
                }
                mpvs.removePropertyValue(pv);
            } else if (v instanceof String) {
                associateObjectForId(pv, v, associatedType);
                mpvs.removePropertyValue(pv);
            }
        } else if (GrailsDomainConfigurationUtil.isBasicType(associatedType)) {
            Object[] values = null;
            if (isArray) {
                values = (Object[]) v;
            } else if (v instanceof String) {
                values = new String[] { (String) v };
            }

            if (values != null) {
                List list = collection instanceof List ? (List) collection : null;
                for (int i = 0; i < values.length; i++) {
                    Object value = values[i];
                    try {
                        Object newValue = getTypeConverter().convertIfNecessary(value, associatedType);
                        if (list != null) {
                            if (i > list.size() - 1) {
                                list.add(i, newValue);
                            } else {
                                list.set(i, newValue);
                            }
                        } else {
                            collection.add(newValue);
                        }
                    } catch (TypeMismatchException e) {
                        // ignore
                    }
                }
                mpvs.removePropertyValue(pv);
            }
        }
    }
}

From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPUtils.java

/**
 * Generates an Element for a given result object
 * @param result - an instance of a class
 * @param recordNum - specifies the record number in the result set
 * @return/*from   ww w . ja  va2 s  .  c  o m*/
 * @throws Exception
 */
private Element getElement2(Object result, String recordNum) throws Exception {
    Element classElement = new Element("class").setAttribute("name", result.getClass().getName())
            .setAttribute("recordNumber", recordNum);
    Map<String, Object> criteriaValueMap = this.getAllNonNullPrimitiveFieldsNamesAndValues(result);
    String criteriaValue = buildCriteriaString(criteriaValueMap);

    String link = null;

    Field[] fields = classCache.getAllFields(result.getClass());
    for (int f = 0; f < fields.length; f++) {
        String criteriaBean = result.getClass().getName();
        Field field = fields[f];
        String fieldName = field.getName();

        if (fieldName.equalsIgnoreCase("serialVersionUID")) {
            continue;
        }
        Element fieldElement = new Element("field").setAttribute("name", fieldName);

        String fieldType = field.getType().getName();
        String targetBean = null;

        if (!(fieldType.startsWith("java") && !(fieldType.endsWith("Collection"))
                || field.getType().isPrimitive())) {
            if (field.getType().getName().endsWith("Collection")) {
                LexEVSSearchUtils searchUtils = new LexEVSSearchUtils(classCache);
                if (searchUtils.getTargetClassName(result.getClass().getName(), fieldName) != null) {
                    targetBean = searchUtils.getTargetClassName(result.getClass().getName(), fieldName);

                    //handle primitive collections
                    if (Class.forName(targetBean).isPrimitive() || targetBean.startsWith("java")) {
                        targetBean = null;
                    }
                }
            } else if (locateClass(fieldType)) {
                targetBean = fieldType;
            }

        }

        if (targetBean != null) {
            if (result.getClass().getPackage().equals(Class.forName(targetBean).getPackage())) {
                targetBean = targetBean.substring(targetBean.lastIndexOf(SystemConstant.DOT) + 1);
                if (criteriaBean.indexOf(SystemConstant.DOT) > 0) {
                    criteriaBean = criteriaBean.substring(criteriaBean.lastIndexOf(SystemConstant.DOT) + 1);
                }
            }
            String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

            link = servletName + "?query=" + targetBean + SystemConstant.AMPERSAND + criteriaBean
                    + criteriaValue + SystemConstant.AMPERSAND + "roleName=" + fieldName;

            fieldElement.setContent(new Element("NestedTest"));

            fieldElement.setAttribute("type", "simple", namespace).setAttribute("href", link, namespace)
                    .setText(methodName);

        } else if (fieldType.endsWith("List")) {
            targetBean = result.getClass().getName();
            String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

            link = servletName + "?query=" + targetBean + SystemConstant.AMPERSAND + criteriaBean
                    + criteriaValue + SystemConstant.AMPERSAND + "roleName=" + fieldName;

            fieldElement.setContent(new Element("NestedTest"));

            fieldElement.setAttribute("type", "simple", namespace).setAttribute("href", link, namespace)
                    .setText(methodName);
        }

        else {
            String fieldValue = "-";
            Object value = null;

            try {
                if (fieldType.indexOf("Collection") > 0 || fieldType.endsWith("HashSet")
                        || fieldType.endsWith("List") || fieldType.endsWith("ArrayList")
                        || fieldType.indexOf("Vector") > 0) {

                    if (((Collection) fields[f].get(result)).size() > 0) {

                        Iterator it = ((Collection) fields[f].get(result)).iterator();

                        Collection collection = (Collection) it.next();
                        String collectionClassName = collection.getClass().getName();
                        classCache.getQualifiedClassName(collectionClassName);

                        fieldValue = String.valueOf(it.next());
                        while (it.hasNext()) {
                            fieldValue += "; " + String.valueOf(it.next());
                        }
                    }

                    if (fieldValue != null) {
                        fieldElement.setText(link);
                    } else {
                        fieldElement.setText("-");
                    }

                } else {
                    if (this.getFieldValue(field, result) != null) {
                        value = getFieldValue(field, result);
                        fieldValue = String.valueOf(value);
                    }
                    fieldElement.setText(fieldValue);
                }

            } catch (Exception ex) {
                fieldValue = "-";
                value = getFieldValue(field, result);
                fieldValue = String.valueOf(value);
                String temp = null;
                for (int s = 0; s < fieldValue.length(); s++) {
                    String charValue = String.valueOf(fieldValue.charAt(s));
                    try {
                        temp += charValue;
                    } catch (Exception e) {
                        temp += " ";
                    }
                }
                if (temp != null) {
                    fieldValue = temp;
                }

                fieldElement.setText(fieldValue);
            }

        }

        classElement.addContent(fieldElement);
    }
    return classElement;
}

From source file:com.yahoo.elide.core.PersistentResource.java

private Collection coerceCollection(Collection<?> values, String fieldName, Class<?> fieldClass) {
    Class<?> providedType = dictionary.getParameterizedType(obj, fieldName);

    // check if collection is of and contains the correct types
    if (fieldClass.isAssignableFrom(values.getClass())) {
        boolean valid = true;
        for (Object member : values) {
            if (member != null && !providedType.isAssignableFrom(member.getClass())) {
                valid = false;// w  ww. j  a  v a2 s .  c  om
                break;
            }
        }
        if (valid) {
            return values;
        }
    }

    ArrayList<Object> list = new ArrayList<>(values.size());
    for (Object member : values) {
        list.add(CoerceUtil.coerce(member, providedType));
    }

    if (Set.class.isAssignableFrom(fieldClass)) {
        return new LinkedHashSet<>(list);
    }

    return list;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

public Collection copyCollection(Collection orig) {
    if (orig == null)
        return null;
    if (orig instanceof Proxy)
        return (Collection) ((Proxy) orig).copy(orig);

    ProxyCollection proxy = getFactoryProxyCollection(orig.getClass());
    return (Collection) proxy.copy(orig);
}