Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

In this page you can find the example usage for java.lang Class getModifiers.

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

Returns the Java language modifiers for this class or interface, encoded in an integer.

Usage

From source file:ome.services.graphs.GraphPathBean.java

/**
 * Process the Hibernate domain object model to initialize this class' instance fields.
 * No other method should write to them.
 * @param sessionFactory the Hibernate session factory
 *//*from  www .ja v  a  2  s . c o  m*/
private void initialize(SessionFactoryImplementor sessionFactory) {
    /* note all the direct superclasses */
    final Map<String, String> superclasses = new HashMap<String, String>();
    final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
    for (final String className : classesMetadata.keySet()) {
        try {
            final Class<?> actualClass = Class.forName(className);
            if (IObject.class.isAssignableFrom(actualClass)) {
                classesBySimpleName.put(actualClass.getSimpleName(), actualClass.asSubclass(IObject.class));
                final Set<String> subclassNames = sessionFactory.getEntityPersister(className)
                        .getEntityMetamodel().getSubclassEntityNames();
                for (final String subclassName : subclassNames) {
                    if (!subclassName.equals(className)) {
                        final Class<?> actualSubclass = Class.forName(subclassName);
                        if (actualSubclass.getSuperclass() == actualClass) {
                            superclasses.put(subclassName, className);
                        }
                    }
                }
            } else {
                log.warn("mapped class " + className + " is not a " + IObject.class.getName());
            }
        } catch (ClassNotFoundException e) {
            log.error("could not instantiate class", e);
        }
    }
    /* note the indirect superclasses and subclasses */
    for (final Entry<String, String> superclassRelationship : superclasses.entrySet()) {
        final String startClass = superclassRelationship.getKey();
        String superclass = superclassRelationship.getValue();
        while (superclass != null) {
            allSuperclasses.put(startClass, superclass);
            allSubclasses.put(superclass, startClass);
            superclass = superclasses.get(superclass);
        }
    }
    /* queue for processing all the properties of all the mapped entities: name, type, nullability */
    final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>();
    final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>();
    for (final Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) {
        final String className = classMetadata.getKey();
        final ClassMetadata metadata = classMetadata.getValue();
        /* note name of identifier property */
        classIdProperties.put(metadata.getEntityName(), metadata.getIdentifierPropertyName());
        /* queue other properties */
        final String[] propertyNames = metadata.getPropertyNames();
        final Type[] propertyTypes = metadata.getPropertyTypes();
        final boolean[] propertyNullabilities = metadata.getPropertyNullability();
        for (int i = 0; i < propertyNames.length; i++) {
            final List<String> propertyPath = Collections.singletonList(propertyNames[i]);
            propertyQueue.add(
                    new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i]));
        }
        final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length);
        propertyNamesSet.addAll(Arrays.asList(propertyNames));
        allPropertyNames.put(className, propertyNamesSet);
    }
    /* process each property to note entity linkages */
    while (!propertyQueue.isEmpty()) {
        final PropertyDetails property = propertyQueue.remove();
        if (ignoreProperty(property.path.get(property.path.size() - 1))) {
            continue;
        }
        /* if the property has a component type, queue the parts for processing */
        if (property.type instanceof ComponentType) {
            final ComponentType componentType = (ComponentType) property.type;
            final String[] componentPropertyNames = componentType.getPropertyNames();
            final Type[] componentPropertyTypes = componentType.getSubtypes();
            final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability();
            for (int i = 0; i < componentPropertyNames.length; i++) {
                final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1);
                componentPropertyPath.addAll(property.path);
                componentPropertyPath.add(componentPropertyNames[i]);
                propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath,
                        componentPropertyTypes[i], componentPropertyNullabilities[i]));
            }
        } else {
            /* determine if another mapped entity class is linked by this property */
            final boolean isAssociatedEntity;
            if (property.type instanceof CollectionType) {
                final CollectionType ct = (CollectionType) property.type;
                isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType()
                        .isEntityType();
            } else {
                isAssociatedEntity = property.type instanceof AssociationType;
            }
            /* the property can link to entities, so process it further */
            String propertyPath = Joiner.on('.').join(property.path);
            /* find if the property is accessible (e.g., not protected) */
            boolean propertyIsAccessible = false;
            String classToInstantiateName = property.holder;
            Class<?> classToInstantiate = null;
            try {
                classToInstantiate = Class.forName(classToInstantiateName);
                while (Modifier.isAbstract(classToInstantiate.getModifiers())) {
                    classToInstantiateName = allSubclasses.get(classToInstantiateName).iterator().next();
                    classToInstantiate = Class.forName(classToInstantiateName);
                }
                try {
                    PropertyUtils.getNestedProperty(classToInstantiate.newInstance(), propertyPath);
                    propertyIsAccessible = true;
                } catch (NoSuchMethodException e) {
                    /* expected for collection properties */
                } catch (NestedNullException e) {
                    log.warn("guessing " + propertyPath + " of " + property.holder + " to be accessible");
                    propertyIsAccessible = true;
                }
            } catch (ReflectiveOperationException e) {
                log.error("could not probe property " + propertyPath + " of " + property.holder, e);
                continue;
            }
            /* build property report line for log */
            final char arrowShaft = property.isNullable ? '-' : '=';
            final StringBuffer sb = new StringBuffer();
            sb.append(property.holder);
            sb.append(' ');
            for (final String propertyName : property.path) {
                sb.append(arrowShaft);
                sb.append(arrowShaft);
                sb.append(propertyName);
            }
            sb.append(arrowShaft);
            sb.append(arrowShaft);
            sb.append("> ");
            final String valueClassName;
            if (isAssociatedEntity) {
                valueClassName = ((AssociationType) property.type).getAssociatedEntityName(sessionFactory);
                sb.append(valueClassName);
            } else {
                valueClassName = null;
                sb.append("value");
            }
            if (property.type.isCollectionType()) {
                sb.append("[]");
            }
            if (!propertyIsAccessible) {
                sb.append(" (inaccessible)");
            }
            /* determine from which class the property is inherited, if at all */
            String superclassWithProperty = null;
            String currentClass = property.holder;
            while (true) {
                currentClass = superclasses.get(currentClass);
                if (currentClass == null) {
                    break;
                } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) {
                    superclassWithProperty = currentClass;
                }
            }
            /* check if the property actually comes from an interface */
            final String declaringClassName = superclassWithProperty == null ? property.holder
                    : superclassWithProperty;
            final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName,
                    property.path.get(0));
            /* report where the property is declared */
            if (superclassWithProperty != null) {
                sb.append(" from ");
                sb.append(superclassWithProperty);
            } else {
                if (interfaceForProperty != null) {
                    sb.append(" see ");
                    sb.append(interfaceForProperty.getName());
                    /* It would be nice to set PropertyDetails to have the interface as the holder,
                     * but then properties would not be unique by declarer class and instance ID. */
                }
                /* entity linkages by non-inherited properties are recorded */
                if (valueClassName == null && property.path.size() > 1) {
                    /* assume that the top-level property suffices for describing simple properties */
                    log.debug("recording " + propertyPath + " as " + property.path.get(0));
                    propertyPath = property.path.get(0);
                }
                final Entry<String, String> classPropertyName = Maps.immutableEntry(property.holder,
                        propertyPath);
                if (valueClassName == null) {
                    simpleProperties.put(property.holder, propertyPath);
                } else {
                    linkedTo.put(property.holder, Maps.immutableEntry(valueClassName, propertyPath));
                    linkedBy.put(valueClassName, classPropertyName);
                }
                final PropertyKind propertyKind;
                if (property.type.isCollectionType()) {
                    propertyKind = PropertyKind.COLLECTION;
                } else if (property.isNullable) {
                    propertyKind = PropertyKind.OPTIONAL;
                } else {
                    propertyKind = PropertyKind.REQUIRED;
                }
                propertyKinds.put(classPropertyName, propertyKind);
                if (propertyIsAccessible) {
                    accessibleProperties.add(classPropertyName);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(sb.toString());
            }
        }
    }
    log.info("initialized graph path bean with " + propertyKinds.size() + " properties");
}

From source file:org.structr.core.module.ModuleService.java

/**
 * Processes the information from the given module and makes them available for the service layer.
 *
 * @param module the module to process//  ww w.j av  a 2 s  .  c  om
 *
 * @throws IOException
 */
private void importResource(Module module) throws IOException {

    Set<String> classes = module.getClasses();

    for (final String name : classes) {

        String className = StringUtils.removeStart(name, ".");

        logger.log(Level.FINE, "Instantiating class {0} ", className);

        try {

            // instantiate class..
            Class clazz = Class.forName(className);

            logger.log(Level.FINE, "Class {0} instantiated: {1}", new Object[] { className, clazz });

            if (!Modifier.isAbstract(clazz.getModifiers())) {

                // register node entity classes
                if (AbstractNode.class.isAssignableFrom(clazz)) {

                    EntityContext.init(clazz);

                    // try to instantiate class
                    try {
                        EntityContext.scanEntity(clazz.newInstance());
                    } catch (Throwable t) {
                    }

                    String simpleName = clazz.getSimpleName();
                    String fullName = clazz.getName();

                    nodeEntityClassCache.put(simpleName, clazz);
                    nodeEntityPackages.add(fullName.substring(0, fullName.lastIndexOf(".")));

                    for (Class interfaceClass : clazz.getInterfaces()) {

                        String interfaceName = interfaceClass.getSimpleName();
                        Set<Class> classesForInterface = interfaceCache.get(interfaceName);

                        if (classesForInterface == null) {

                            classesForInterface = new LinkedHashSet<Class>();

                            interfaceCache.put(interfaceName, classesForInterface);

                        }

                        classesForInterface.add(clazz);

                    }

                }

                // register entity classes
                if (AbstractRelationship.class.isAssignableFrom(clazz)) {

                    EntityContext.init(clazz);

                    // try to instantiate class
                    try {
                        EntityContext.scanEntity(clazz.newInstance());
                    } catch (Throwable t) {
                    }

                    String simpleName = clazz.getSimpleName();
                    String fullName = clazz.getName();

                    relationshipClassCache.put(simpleName, clazz);
                    relationshipPackages.add(fullName.substring(0, fullName.lastIndexOf(".")));

                    for (Class interfaceClass : clazz.getInterfaces()) {

                        String interfaceName = interfaceClass.getSimpleName();
                        Set<Class> classesForInterface = interfaceCache.get(interfaceName);

                        if (classesForInterface == null) {

                            classesForInterface = new LinkedHashSet<Class>();

                            interfaceCache.put(interfaceName, classesForInterface);

                        }

                        classesForInterface.add(clazz);

                    }
                }

                // register services
                if (Service.class.isAssignableFrom(clazz)) {

                    Services.registerServiceClass(clazz);
                }

                // register agents
                if (Agent.class.isAssignableFrom(clazz)) {

                    String simpleName = clazz.getSimpleName();
                    String fullName = clazz.getName();

                    agentClassCache.put(simpleName, clazz);
                    agentPackages.add(fullName.substring(0, fullName.lastIndexOf(".")));

                }
            }

        } catch (Throwable t) {
        }

    }

}

From source file:org.obsidian.test.TestAbstract.java

public <T> String buildConstructionStringFromType(Class<T> type, Constructor[] visitedConstructors) {

    //initialize construction String 
    String constructionString;//from  w  w  w  . j  a  v  a2s  .  c o m

    //append equality method types
    appendEqualityMethodTypes(type);

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    //if class is abstract, replace with concrete substitution
    if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        type = Helpers.getConcreteSubstitution(type);
    }

    //type's simple name
    String name = type.getSimpleName();

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    if (Helpers.PRIMITIVE_CONSTRUCTIONS.get(name) != null) {
        //get construction from PRIMITIVE_CONSTRUCTIONS
        constructionString = Helpers.PRIMITIVE_CONSTRUCTIONS.get(name);
    } else if (type.isArray()) {
        int numberOfDimensions = StringUtils.countMatches(name, "[]");

        constructionString = name.replace("[]", "");

        for (int i = 0; i < numberOfDimensions; i++) {
            constructionString = constructionString + "[0]";
        }

        constructionString = "new " + constructionString;

    } else if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        constructionString = "null";
    } else if (type.getConstructors().length == 0) {
        constructionString = "null";
    } else {
        //not visited constructors
        ArrayList<Constructor> NVC = Helpers.notVisitedConstructors(type.getConstructors(),
                visitedConstructors);

        Constructor constructor = Helpers.getConstructorWithLeastParametersFromList(NVC);

        if (NVC.isEmpty()) {
            constructionString = "null";
        } else if (constructor.getExceptionTypes().length > 0) {
            constructionString = "null";
        } else {

            visitedConstructors = Helpers.addConstructor(visitedConstructors, constructor);
            constructionString = "new " + name + "(";
            Class[] parameters = constructor.getParameterTypes();
            for (int i = 0; i < parameters.length; i++) {
                constructionString = constructionString
                        + buildConstructionStringFromType(parameters[i], visitedConstructors) + ",";
            }
            if (parameters.length != 0) {
                constructionString = constructionString.substring(0, constructionString.length() - 1);
            }
            constructionString = constructionString + ")";
        }
    }

    //this will prevent ambiguity in constructors with parmeter that 
    //cannot be constructed
    if (constructionString.contains("null")) {
        constructionString = "null";
    }

    return constructionString;
}

From source file:ome.services.graphs.AbstractHierarchyGraphSpec.java

/**
 * Performs sanity checks on the entries found in {@link ExtendedMetadata}.
 * Primarily, this prevents new types from not being properly specified
 * in spec.xml.//from  w  w w. ja  v a 2 s.co  m
 */
@Override
public void setExtendedMetadata(ExtendedMetadata em) {
    super.setExtendedMetadata(em);

    // First calculate the number of unique top-level paths
    List<String> uniquePaths = new ArrayList<String>();
    for (GraphEntry entry : entries) {
        String topLevel = entry.path("")[0];
        if (!uniquePaths.contains(topLevel)) {
            uniquePaths.add(topLevel);
        }
    }

    // Now we check if this represents all the hierarchy types
    // in the system.
    Set<Class<IObject>> types = getTypes(em);
    if (types.size() != uniquePaths.size()) {
        throw new FatalBeanException(
                "Mismatch between types defined and those found: " + entries + "<> " + types);
    }

    TYPE: for (Class<?> type : types) {
        String simpleName = type.getSimpleName();
        for (int i = 0; i < entries.size(); i++) {
            GraphEntry entry = entries.get(i);
            if (entry.path("").length > 1) {
                // This not part of our hierarchy, but some subpath
                // ignore it.
                continue;
            }
            if (simpleName.equals(entry.getName().substring(1))) {
                this.types[i] = type;
                if (Modifier.isAbstract(type.getModifiers())) {
                    this.isAbstract[i] = true;
                }
                continue TYPE;
            }
        }
        throw new FatalBeanException("Could not find entry: " + simpleName);
    }
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException/*from  www.ja v a 2 s  . c o  m*/
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:org.evosuite.testcase.ImportsTestCodeVisitor.java

/** {@inheritDoc} */
@Override/*from   w ww.  jav a  2s. com*/
public void visitFieldStatement(FieldStatement statement) {
    Throwable exception = getException(statement);

    VariableReference retval = statement.getReturnValue();
    GenericField field = statement.getField();

    getClassName(retval);

    if (!field.isStatic()) {
        VariableReference source = statement.getSource();
        getClassName(source);
    } else {
        getClassName(field.getField().getDeclaringClass());
    }
    if (exception != null) {
        Class<?> ex = exception.getClass();
        while (!Modifier.isPublic(ex.getModifiers()))
            ex = ex.getSuperclass();
        getClassName(ex);
    }
    visitAssertions(statement);
}

From source file:org.unitils.inject.InjectModule.java

/**
 * Creates an objects of the given fields' declared type and assigns it to this field on the given testObject
 *
 * @param testObject        The test instance, not null
 * @param testedObjectField The tested object field, not null
 *///from   w ww. j  a v  a 2 s . c o m
protected void createObjectForField(Object testObject, Field testedObjectField) {
    Class<?> declaredClass = testedObjectField.getType();
    if (declaredClass.isInterface()) {
        logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type "
                + testedObjectField.getType().getSimpleName()
                + " which is an interface type. It is not automatically instantiated.");

    } else if (isAbstract(declaredClass.getModifiers())) {
        logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type "
                + testedObjectField.getDeclaringClass().getSimpleName()
                + " which is an abstract class. It is not automatically instantiated.");

    } else {
        try {
            declaredClass.getDeclaredConstructor();
            Object instance = createInstanceOfType(declaredClass, true);
            setFieldValue(testObject, testedObjectField, instance);
        } catch (NoSuchMethodException e) {
            logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type "
                    + testedObjectField.getDeclaringClass().getSimpleName()
                    + " which has no default (parameterless) constructor. It is not automatically instantiated.");
        }
    }
}

From source file:org.evosuite.testcarver.testcase.EvoTestCaseCodeGenerator.java

@Override
public void createMapInitStmt(final CaptureLog log, final int logRecNo) {
    try {/* w  w w.ja va  2 s  .c o  m*/
        final int oid = log.objectIds.get(logRecNo);
        final Object[] params = log.params.get(logRecNo);
        String collTypeName = log.getTypeName(oid);
        Class<?> collType = getClassForName(collTypeName);

        // -- determine if an alternative collection must be used for code generation
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(collType.getModifiers());
        if (!isPublic || !hasDefaultConstructor(collType)) {
            collType = HashMap.class;
        }

        // -- create code for instantiating collection

        final List<VariableReference> noParams = Collections.emptyList();
        final ConstructorStatement constrStmt = new ConstructorStatement(testCase,
                new GenericConstructor(collType.getConstructor(new Class<?>[0]), collType), noParams);

        final VariableReference collRef = testCase.addStatement(constrStmt);
        this.oidToVarRefMap.put(oid, collRef);

        // --- fill collection

        MethodStatement methodStmt;
        Integer argOID; // is either an oid or null
        ArrayList<VariableReference> paramList = new ArrayList<VariableReference>();

        for (int i = 0; i < params.length; i++) {
            argOID = (Integer) params[i];
            if (argOID == null) {

                paramList.add(testCase.addStatement(new NullStatement(testCase, Object.class)));

            } else {
                paramList.add(this.oidToVarRefMap.get(argOID));
            }

            if (i % 2 == 1) {

                final Method method = collType.getMethod("put", Object.class, Object.class);

                replaceNullWithNullReferences(paramList, Object.class, Object.class);

                methodStmt = new MethodStatement(testCase, new GenericMethod(method, collType), collRef,
                        paramList);
                testCase.addStatement(methodStmt);
                paramList = new ArrayList<VariableReference>(2);
            }

        }
    } catch (final Exception e) {
        CodeGeneratorException.propagateError(e,
                "[logRecNo = %s] - an unexpected error occurred while creating map init stmt", logRecNo);
    }
}

From source file:jenkins.scm.api.SCMHeadMixinEqualityGenerator.java

/**
 * Creates the {@link SCMHeadMixin.Equality} instance.
 *
 * @param type the {@link SCMHead} type to create the instance for.
 * @return the {@link SCMHeadMixin.Equality} instance.
 *//*from  www  .j a va2s .c om*/
@NonNull
private SCMHeadMixin.Equality create(@NonNull Class<? extends SCMHead> type) {
    Map<String, Method> properties = new TreeMap<String, Method>();
    for (Class clazz : (List<Class>) ClassUtils.getAllInterfaces(type)) {
        if (!SCMHeadMixin.class.isAssignableFrom(clazz)) {
            // not a mix-in
            continue;
        }
        if (SCMHeadMixin.class == clazz) {
            // no need to check this by reflection
            continue;
        }
        if (!Modifier.isPublic(clazz.getModifiers())) {
            // not public
            continue;
        }
        // this is a mixin interface, only look at declared properties;
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getReturnType() == Void.class) {
                // nothing to do with us
                continue;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                // should never get here
                continue;
            }
            if (Modifier.isStatic(method.getModifiers())) {
                // might get here with Java 8
                continue;
            }
            if (method.getParameterTypes().length != 0) {
                // not a property
                continue;
            }
            String name = method.getName();
            if (!name.matches("^((is[A-Z0-9_].*)|(get[A-Z0-9_].*))$")) {
                // not a property
                continue;
            }
            if (name.startsWith("is")) {
                name = "" + Character.toLowerCase(name.charAt(2))
                        + (name.length() > 3 ? name.substring(3) : "");
            } else {
                name = "" + Character.toLowerCase(name.charAt(3))
                        + (name.length() > 4 ? name.substring(4) : "");
            }
            if (properties.containsKey(name)) {
                // a higher priority interface already defined the method
                continue;
            }
            properties.put(name, method);
        }
    }
    if (properties.isEmpty()) {
        // no properties to consider
        return new ConstantEquality();
    }
    if (forceReflection) {
        return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));
    }
    // now we define the class
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    String name = SCMHeadMixin.class.getPackage().getName() + ".internal." + type.getName();

    // TODO Move to 1.7 opcodes once baseline 1.612+
    cw.visit(Opcodes.V1_6, ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(SCMHeadMixin.Equality.class) });
    generateDefaultConstructor(cw);
    generateEquals(cw, properties.values());
    byte[] image = cw.toByteArray();

    Class<? extends SCMHeadMixin.Equality> c = defineClass(name, image, 0, image.length)
            .asSubclass(SCMHeadMixin.Equality.class);

    try {
        return c.newInstance();
    } catch (InstantiationException e) {
        // fallback to reflection
    } catch (IllegalAccessException e) {
        // fallback to reflection
    }
    return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));

}

From source file:org.evosuite.testcarver.testcase.EvoTestCaseCodeGenerator.java

@Override
public void createCollectionInitStmt(final CaptureLog log, final int logRecNo) {
    try {//from w w w  .ja v a 2  s  . com
        final int oid = log.objectIds.get(logRecNo);
        final Object[] params = log.params.get(logRecNo);
        String collTypeName = log.getTypeName(oid);
        Class<?> collType = getClassForName(collTypeName);

        // -- determine if an alternative collection must be used for code generation
        final boolean isPublic = java.lang.reflect.Modifier.isPublic(collType.getModifiers());
        if (!isPublic || !hasDefaultConstructor(collType)) {
            if (Set.class.isAssignableFrom(collType)) {
                collTypeName = HashSet.class.getName();
                collType = HashSet.class;
            } else if (List.class.isAssignableFrom(collType)) {
                collTypeName = ArrayList.class.getName();
                collType = ArrayList.class;
            } else if (Queue.class.isAssignableFrom(collType)) {
                collTypeName = ArrayDeque.class.getName();
                collType = ArrayDeque.class;
            } else {
                CodeGeneratorException.propagateError("[logRecNo = %s] - collection %s is not supported",
                        logRecNo, collType);
            }
        }

        // -- create code for instantiating collection

        final List<VariableReference> noParams = Collections.emptyList();
        final ConstructorStatement constrStmt = new ConstructorStatement(testCase,
                new GenericConstructor(collType.getConstructor(new Class<?>[0]), collType), noParams);

        final VariableReference collRef = testCase.addStatement(constrStmt);
        this.oidToVarRefMap.put(oid, collRef);

        // --- fill collection

        MethodStatement methodStmt;
        Integer argOID; // is either an oid or null
        ArrayList<VariableReference> paramList;
        Method method;

        for (int i = 0; i < params.length; i++) {
            paramList = new ArrayList<VariableReference>(1);
            argOID = (Integer) params[i];
            if (argOID == null || !this.oidToVarRefMap.containsKey(argOID)) {
                VariableReference var = testCase.addStatement(new NullStatement(testCase, Object.class));
                paramList.add(var);
            } else {
                VariableReference var = this.oidToVarRefMap.get(argOID);
                paramList.add(var);
            }

            method = collType.getMethod("add", Object.class);
            methodStmt = new MethodStatement(testCase, new GenericMethod(method, collType), collRef, paramList);
            testCase.addStatement(methodStmt);
        }
    } catch (final Exception e) {
        CodeGeneratorException.propagateError(
                "[logRecNo = %s] - an unexpected error occurred while creating collection init stmt", logRecNo,
                e);
    }
}