Example usage for java.lang Class isInstance

List of usage examples for java.lang Class isInstance

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInstance(Object obj);

Source Link

Document

Determines if the specified Object is assignment-compatible with the object represented by this Class .

Usage

From source file:de.ovgu.featureide.core.typecheck.helper.FujiWrapper.java

/**
 * Iterates a abstract syntax tree, searching for ASTNodes of the specific
 * type/* w  w  w. j  a va 2s.co  m*/
 * 
 * @param node
 *            the current node
 * @param type
 *            the node type to look for
 * @return a list of nodes of the given type
 */
@SuppressWarnings("rawtypes")
public static <T> List<T> getChildNodesByType(ASTNode node, Class<T> type) {
    List<T> list = new ArrayList<T>();
    for (int i = 0; i < node.getNumChild(); i++) {
        ASTNode c = node.getChild(i);
        if (type.isInstance(c)) {
            list.add(type.cast(c));
        }
        list.addAll(getChildNodesByType(c, type));
    }
    return list;
}

From source file:Main.java

@SuppressWarnings({ "unchecked" })
public static <X extends Node> List<X> getChildNodes(Node node, Class<X> type) {
    final NodeList nodelist = node.getChildNodes();
    ArrayList<X> list = new ArrayList<X>(nodelist.getLength());
    for (int i = 0; i < nodelist.getLength(); i++) {
        final Node child = nodelist.item(i);
        if (type.isInstance(child)) {
            list.add((X) child);//from w  w w  .j a  v a2s.  c  o m
        }
    }
    return list;
}

From source file:Main.java

/**
 * Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform.
 *//* w ww.ja v  a2 s.  co m*/
private static sun.misc.Unsafe getUnsafe() {
    sun.misc.Unsafe unsafe = null;
    try {
        unsafe = AccessController.doPrivileged(new PrivilegedExceptionAction<Unsafe>() {
            @Override
            public sun.misc.Unsafe run() throws Exception {
                Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;

                for (Field f : k.getDeclaredFields()) {
                    f.setAccessible(true);
                    Object x = f.get(null);
                    if (k.isInstance(x)) {
                        return k.cast(x);
                    }
                }
                // The sun.misc.Unsafe field does not exist.
                return null;
            }
        });
    } catch (Throwable e) {
        // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError
        // for Unsafe.
    }
    return unsafe;
}

From source file:Main.java

/**
 * Find a single value of the given type in the given Collection.
 *
 * @param collection the Collection to search
 * @param type       the type to look for
 * @return a value of the given type found if there is a clear match,
 * or {@code null} if none or more than one such value found
 *//*from  w  ww.  j a va2s .c o m*/
@SuppressWarnings("unchecked")
public static <T> T findValueOfType(Collection<?> collection, Class<T> type) {
    if (isEmpty(collection)) {
        return null;
    }
    T value = null;
    for (Object element : collection) {
        if (type == null || type.isInstance(element)) {
            if (value != null) {
                // More than one value found... no clear single value.
                return null;
            }
            value = (T) element;
        }
    }
    return value;
}

From source file:Main.java

/**
 * Convenience method for searching above the given component in the component
 * hierarchy and returns the first object of the given type it finds, or
 * <code>null</code> if no such parent was found.
 * <p>//from   w  ww. j  ava  2s .c o  m
 * The reason this method exists is for tidyness of the calling code, as no
 * longer a explicit cast is needed.
 * 
 * @param aType
 *          the type of the parent to find, cannot be <code>null</code>;
 * @param aComponent
 *          the component to search in the hierarchy, cannot be
 *          <code>null</code>.
 * @return the requested ancestor, or <code>null</code> if not found.
 * @see SwingUtilities#getAncestorOfClass(Class, Component)
 */
@SuppressWarnings("unchecked")
public static <T> T getAncestorOfClass(final Class<T> aType, final Component aComponent) {
    if ((aComponent == null) || (aType == null)) {
        return null;
    }

    Container parent = aComponent.getParent();
    while ((parent != null) && !(aType.isInstance(parent))) {
        parent = parent.getParent();
    }

    return (T) parent;
}

From source file:me.tfeng.play.mongodb.MongoDbTypeConverter.java

public static <S, T> S convertToMongoDbType(Class<S> mongoClass, T data) {
    if (data == null) {
        return null;
    } else if (mongoClass.isInstance(data)) {
        return mongoClass.cast(data);
    } else {//from www . ja  v  a  2  s. c o  m
        @SuppressWarnings("unchecked")
        Converter<S, T> converter = (Converter<S, T>) CONVERTER_MAP
                .get(ImmutablePair.of(mongoClass, data.getClass()));
        if (converter != null) {
            return converter.convertToMongoDbType(data);
        } else if (DBObject.class.isAssignableFrom(mongoClass) && data instanceof String) {
            return mongoClass.cast(JSON.parse((String) data));
        } else {
            return null;
        }
    }
}

From source file:me.tfeng.play.mongodb.MongoDbTypeConverter.java

public static <S, T> T convertFromMongoDbType(Class<T> dataClass, S object) {
    if (object == null) {
        return null;
    } else if (dataClass.isInstance(object)) {
        return dataClass.cast(object);
    } else {/*from   www . j  a  v a2 s.  c o  m*/
        @SuppressWarnings("unchecked")
        Converter<S, T> converter = (Converter<S, T>) CONVERTER_MAP
                .get(ImmutablePair.of(object.getClass(), dataClass));
        if (converter != null) {
            return converter.convertFromMongoDbType(object);
        } else if (String.class.isAssignableFrom(dataClass) && object instanceof DBObject) {
            return dataClass.cast(JSON.serialize(object));
        } else {
            return null;
        }
    }
}

From source file:org.eclipse.virgo.ide.ui.editors.PdeCompatibilityUtil.java

public static boolean isSystemFileEditorInput(IEditorInput input) {
    if (isEclipse34) {
        Class<?> systemFileEditorInputClass;
        try {//ww w  .  jav  a2s  .c  om
            systemFileEditorInputClass = Class
                    .forName("org.eclipse.pde.internal.ui.editor.SystemFileEditorInput");
            return systemFileEditorInputClass.isInstance(input);
        } catch (ClassNotFoundException e) {
            isEclipse34 = false;
        } catch (Throwable e) {
            SpringCore.log(new Status(IStatus.ERROR, ServerIdeUiPlugin.PLUGIN_ID,
                    "Failed to check fo instance of SystemFileEditorInput"));
            isEclipse34 = false;
        }
    }
    return false;
}

From source file:com.proofpoint.event.client.EventDataType.java

static void validateFieldValueType(Object value, Class<?> expectedType) {
    Preconditions.checkNotNull(value, "value is null");
    Preconditions.checkArgument(expectedType.isInstance(value), "Expected 'value' to be a "
            + expectedType.getSimpleName() + " but it is a " + value.getClass().getName());
}

From source file:NumberUtils.java

/**
 * Convert the given number into an instance of the given target class.
 *
 * @param number      the number to convert
 * @param targetClass the target class to convert to
 * @return the converted number//  ww  w.  j av  a2 s  .c  o  m
 * @throws IllegalArgumentException if the target class is not supported
 *                                  (i.e. not a standard Number subclass as included in the JDK)
 * @see java.lang.Byte
 * @see java.lang.Short
 * @see java.lang.Integer
 * @see java.lang.Long
 * @see java.math.BigInteger
 * @see java.lang.Float
 * @see java.lang.Double
 * @see java.math.BigDecimal
 */
public static Number convertNumberToTargetClass(Number number, Class targetClass)
        throws IllegalArgumentException {

    if (targetClass.isInstance(number)) {
        return number;
    } else if (targetClass.equals(Byte.class)) {
        long value = number.longValue();
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return number.byteValue();
    } else if (targetClass.equals(Short.class)) {
        long value = number.longValue();
        if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return number.shortValue();
    } else if (targetClass.equals(Integer.class)) {
        long value = number.longValue();
        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return number.intValue();
    } else if (targetClass.equals(Long.class)) {
        return number.longValue();
    } else if (targetClass.equals(Float.class)) {
        return number.floatValue();
    } else if (targetClass.equals(Double.class)) {
        return number.doubleValue();
    } else if (targetClass.equals(BigInteger.class)) {
        return BigInteger.valueOf(number.longValue());
    } else if (targetClass.equals(BigDecimal.class)) {
        // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
        // (see BigDecimal javadoc for details)
        return new BigDecimal(number.toString());
    } else {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
                + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
    }
}