Example usage for java.lang Class equals

List of usage examples for java.lang Class equals

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

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

Usage

From source file:org.openmrs.module.openhmis.cashier.api.ReceiptNumberGeneratorFactory.java

/**
 * Locates and instantiates all classes that implement {@link IReceiptNumberGenerator} in the current classpath.
 * @return The instantiated receipt number generators.
 * @should Locate all classes that implement IReceiptNumberGenerator
 * @should Not throw an exception if the class instantiation fails
 * @should Use the existing instance for the currently defined generator
 */// w  w w .  j  a va  2  s .  co m
public static IReceiptNumberGenerator[] locateGenerators() {
    // Search for any modules that define classes which implement the IReceiptNumberGenerator interface
    Reflections reflections = new Reflections("org.openmrs.module");
    List<Class<? extends IReceiptNumberGenerator>> classes = new ArrayList<Class<? extends IReceiptNumberGenerator>>();
    for (Class<? extends IReceiptNumberGenerator> cls : reflections
            .getSubTypesOf(IReceiptNumberGenerator.class)) {
        // We only care about public instantiable classes so ignore others
        if (!cls.isInterface() && !Modifier.isAbstract(cls.getModifiers())
                && Modifier.isPublic(cls.getModifiers())) {
            classes.add(cls);
        }
    }

    // Now attempt to instantiate each found class
    List<IReceiptNumberGenerator> instances = new ArrayList<IReceiptNumberGenerator>();
    for (Class<? extends IReceiptNumberGenerator> cls : classes) {
        if (generator != null && cls.equals(generator.getClass())) {
            instances.add(generator);
        } else {
            try {
                instances.add(cls.newInstance());
            } catch (Exception ex) {
                // We don't care about specific exceptions here.  Just log and ignore the class
                LOG.warn("Could not instantiate the '" + cls.getName() + "' class.  It will be ignored.");
            }
        }
    }

    // Finally, copy the instances to an array
    IReceiptNumberGenerator[] results = new IReceiptNumberGenerator[instances.size()];
    instances.toArray(results);

    return results;
}

From source file:com.frame.base.utils.ReflectionUtils.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. (Taken from http://www.artima.com/weblogs/viewpost.jsp?thread=208860. Thanks
 * mathieu.grenonville for finding this solution!)
 * /*from   w w w . j av a2 s.  c o m*/
 * @param baseClass
 *            the base class
 * @param childClass
 *            the child class
 * @return a list of the raw classes for the actual type arguments.
 */
@SuppressWarnings("rawtypes")
public static <T> List<Class<?>> getTypeArguments(Class<T> baseClass, Class<? extends T> childClass) {
    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = childClass;
    // start walking up the inheritance hierarchy until we hit baseClass
    while (!getClass(type).equals(baseClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just
            // keep going.
            type = ((Class) type).getGenericSuperclass();
        } else {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Class<?> rawType = (Class) parameterizedType.getRawType();

            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
            for (int i = 0; i < actualTypeArguments.length; i++) {
                resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
            }

            if (!rawType.equals(baseClass)) {
                type = rawType.getGenericSuperclass();
            }
        }
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible)
    // the raw class for that type argument.
    Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = ((Class) type).getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }
    List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
    // resolve types by chasing down type variables.
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType)) {
            baseType = resolvedTypes.get(baseType);
        }
        typeArgumentsAsClasses.add(getClass(baseType));
    }
    return typeArgumentsAsClasses;
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Traverse the inheritance tree of a class, including the class itself.
 * // w w w. java  2  s  . c o  m
 * @param <T>
 *            the type to return as traversal result.
 * @param clazz
 *            the class to traverse
 * @param upTillClass
 *            the top level class to stop at
 * @param includeInterfaces
 *            true to traverse interfaces, false not to
 * @param visitor
 *            the visitor to be called on visiting each class on the
 *            inheritance tree. If the onVisit() method returns null, the
 *            traversal will continue, otherwise it will stop and return the
 *            value as overall result.
 * @return the value returned by the visitor's.
 */
public static <T> T traverseInheritance(Class<?> clazz, Class<?> upTillClass, boolean includeInterfaces,
        IClassVisitor<T> visitor) {
    if (!includeInterfaces && clazz.isInterface()) {
        return null;
    }
    if (upTillClass != null && upTillClass.equals(clazz)) {
        return visitor.onVisit(clazz);
    }
    if (Object.class.equals(clazz)) {
        return null;
    }
    T result = visitor.onVisit(clazz);
    if (result != null) {
        return result;
    }
    for (Class<?> intf : clazz.getInterfaces()) {
        result = traverseInheritance(intf, upTillClass, includeInterfaces, visitor);
        if (result != null) {
            return result;
        }
    }
    Class<?> parentClass = clazz.getSuperclass();
    if (parentClass != null) {
        result = traverseInheritance(parentClass, upTillClass, includeInterfaces, visitor);
    }
    return result;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

private static boolean isByRef(Class<?> param, Annotation[] annotations) {
    // if parameter has ByValue annotation, it is ByValueParameter
    if (containsAnnotation(annotations, ByValueParameter.class))
        return false;

    // if this is primitive or wrapper type, it is ByValueParameter
    if (param.isPrimitive() || param.equals(String.class) || Primitives.allWrapperTypes().contains(param))
        return false;

    // if this is enum, it is ByValueParameter
    if (param.isEnum())
        return false;

    // if parameter class has ByValueParameter annotation, it is ByValueParameter
    if (param.isAnnotationPresent(ByValueParameter.class))
        return false;

    // otherwise it is ByRefParameter
    return true;//from   w  ww .jav a2  s . c o  m
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

private static <T> boolean hasPermissionFilters(Class<T> resultClass) throws GenericException {
    return resultClass.equals(AIP.class) || resultClass.equals(IndexedAIP.class)
            || resultClass.equals(Representation.class) || resultClass.equals(IndexedRepresentation.class)
            || resultClass.equals(IndexedFile.class) || resultClass.equals(IndexedPreservationEvent.class);
}

From source file:de.skubware.opentraining.activity.settings.sync.WgerJSONParser.java

/**
 * A generic parsing method for parsing JSON to SportsEquipment, Muscle or Locale.
 *//*  w ww. j  a v  a  2 s.c om*/
private static <T> SparseArray<T> parse(String jsonString, Class<T> c) throws JSONException {
    JSONObject mainObject = new JSONObject(jsonString);
    Log.d(TAG, "jsonString: " + mainObject.toString());
    JSONArray mainArray = mainObject.getJSONArray("objects");

    SparseArray<T> sparseArray = new SparseArray<T>();

    // parse each exercise of the JSON Array
    for (int i = 0; i < mainArray.length(); i++) {
        JSONObject singleObject = mainArray.getJSONObject(i);

        Integer id = singleObject.getInt("id");
        Object parsedObject;
        if (c.equals(Muscle.class)) {
            // handle Muscles
            String name = singleObject.getString("name");
            parsedObject = mDataProvider.getMuscleByName(name);

            if (parsedObject == null)
                Log.e(TAG, "Could not find Muscle: " + name);

        } else if (c.equals(SportsEquipment.class)) {
            // handle SportsEquipment
            String name = singleObject.getString("name");
            parsedObject = mDataProvider.getEquipmentByName(name);

            if (parsedObject == null)
                Log.e(TAG, "Could not find SportsEquipment: " + name);

        } else if (c.equals(Locale.class)) {
            // handle Locales
            String short_name = singleObject.getString("short_name");
            parsedObject = new Locale(short_name);

            if (short_name == null || short_name.equals(""))
                Log.e(TAG, "Error, no short_name=" + short_name);

        } else if (c.equals(LicenseType.class)) {
            // handle licenses
            String short_name = singleObject.getString("short_name");

            parsedObject = mDataProvider.getLicenseTypeByName(short_name);

            if (short_name == null || short_name.equals(""))
                Log.e(TAG, "Error, no short_name=" + short_name);

        } else {
            throw new IllegalStateException(
                    "parse(String, Class<T>) cannot be applied for class: " + c.toString());
        }

        sparseArray.put(id, (T) parsedObject);

    }

    return sparseArray;
}

From source file:org.jfree.chart.demo.SymbolicXYPlotDemo.java

/**
 * Transform an primitive array to an object array.
 * /* www. ja  v  a 2s.c  o  m*/
 * @param arr
 *           the array.
 * @return an array.
 */
private static Object toArray(final Object arr) {

    if (arr == null) {
        return arr;
    }

    final Class cls = arr.getClass();
    if (!cls.isArray()) {
        return arr;
    }

    Class compType = cls.getComponentType();
    int dim = 1;
    while (!compType.isPrimitive()) {
        if (!compType.isArray()) {
            return arr;
        } else {
            dim++;
            compType = compType.getComponentType();
        }
    }

    final int[] length = new int[dim];
    length[0] = Array.getLength(arr);
    Object[] newarr = null;

    try {
        if (compType.equals(Integer.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Integer"), length);
        } else if (compType.equals(Double.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Double"), length);
        } else if (compType.equals(Long.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Long"), length);
        } else if (compType.equals(Float.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Float"), length);
        } else if (compType.equals(Short.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Short"), length);
        } else if (compType.equals(Byte.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Byte"), length);
        } else if (compType.equals(Character.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Character"), length);
        } else if (compType.equals(Boolean.TYPE)) {
            newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Boolean"), length);
        }
    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
    }

    for (int i = 0; i < length[0]; i++) {
        if (dim != 1) {
            newarr[i] = toArray(Array.get(arr, i));
        } else {
            newarr[i] = Array.get(arr, i);
        }
    }
    return newarr;
}

From source file:com.evolveum.midpoint.prism.xml.XmlTypeConverter.java

public static String toXmlTextContent(Object val, QName elementName) {
    if (val == null) {
        // if no value is specified, do not create element
        return null;
    }/*from   w ww  .  j ava2 s.c  o m*/
    Class type = XsdTypeMapper.getTypeFromClass(val.getClass());
    if (type == null) {
        throw new IllegalArgumentException(
                "No type mapping for conversion: " + val.getClass() + "(element " + elementName + ")");
    }
    if (type.equals(String.class)) {
        return (String) val;
    }
    if (type.equals(PolyString.class)) {
        return ((PolyString) val).getNorm();
    } else if (type.equals(char.class) || type.equals(Character.class)) {
        return ((Character) val).toString();
    } else if (type.equals(File.class)) {
        return ((File) val).getPath();
    } else if (type.equals(int.class) || type.equals(Integer.class)) {
        return ((Integer) val).toString();
    } else if (type.equals(long.class) || type.equals(Long.class)) {
        return ((Long) val).toString();
    } else if (type.equals(byte.class) || type.equals(Byte.class)) {
        return ((Byte) val).toString();
    } else if (type.equals(float.class) || type.equals(Float.class)) {
        return ((Float) val).toString();
    } else if (type.equals(double.class) || type.equals(Double.class)) {
        return ((Double) val).toString();
    } else if (type.equals(byte[].class)) {
        byte[] binaryData = (byte[]) val;
        return Base64.encodeBase64String(binaryData);
    } else if (type.equals(Boolean.class)) {
        Boolean bool = (Boolean) val;
        if (bool.booleanValue()) {
            return XsdTypeMapper.BOOLEAN_XML_VALUE_TRUE;
        } else {
            return XsdTypeMapper.BOOLEAN_XML_VALUE_FALSE;
        }
    } else if (type.equals(BigInteger.class)) {
        return ((BigInteger) val).toString();
    } else if (type.equals(BigDecimal.class)) {
        return ((BigDecimal) val).toString();
    } else if (type.equals(GregorianCalendar.class)) {
        XMLGregorianCalendar xmlCal = createXMLGregorianCalendar((GregorianCalendar) val);
        return xmlCal.toXMLFormat();
    } else if (XMLGregorianCalendar.class.isAssignableFrom(type)) {
        return ((XMLGregorianCalendar) val).toXMLFormat();
    } else if (Duration.class.isAssignableFrom(type)) {
        return ((Duration) val).toString();
    } else if (type.equals(ItemPath.class)) {
        XPathHolder xpath = new XPathHolder((ItemPath) val);
        return xpath.getXPath();
    } else {
        throw new IllegalArgumentException(
                "Unknown type for conversion: " + type + "(element " + elementName + ")");
    }
}

From source file:com.project.framework.util.ReflectionUtils.java

/**
 * ??, Class??./*from  www.j  a  v  a2 s.  c  o  m*/
 * , null Class Array.
 * 
 * @param clazz
 * @param interfaze
 * @param index
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Class getInterfaceGenricType(final Class clazz, final Class interfaze, final int index) {

    if (!interfaze.isInterface())
        throw new IllegalArgumentException("interfaze must be a interface.");

    if (!interfaze.isAssignableFrom(clazz))
        throw new IllegalArgumentException("clazz must be implemnet form interfaze");

    Type[] genTypes = clazz.getGenericInterfaces();

    for (Type genType : genTypes) {
        if (genType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) genType;

            if (interfaze.equals(pt.getRawType())) {
                Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

                if (index >= params.length || index < 0) {
                    logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName()
                            + "'s Parameterized Type: " + params.length);
                    return Object.class;
                }
                if (!(params[index] instanceof Class)) {
                    logger.warn(clazz.getSimpleName()
                            + " not set the actual class on superclass generic parameter");
                    return Object.class;
                }

                return (Class) params[index];
            }
        }
    }

    return null;
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

private static <T> String getIndexName(Class<T> resultClass) throws GenericException {
    String indexName = null;//from   w  w w. j  a  va 2  s.  c  om
    if (resultClass.equals(ViewerDatabase.class)) {
        indexName = ViewerSafeConstants.SOLR_INDEX_DATABASE_COLLECTION_NAME;
    } else if (resultClass.equals(SavedSearch.class)) {
        indexName = ViewerSafeConstants.SOLR_INDEX_SEARCHES_COLLECTION_NAME;
    } else if (resultClass.equals(ViewerRow.class)) {
        throw new GenericException(
                "Can not determine collection name from " + ViewerRow.class.getName() + " class name");
    } else {
        throw new GenericException("Cannot find class index name: " + resultClass.getName());
    }
    return indexName;
}