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:com.excilys.ebi.bank.util.Asserts.java

public static void isInstanceOf(Class<?> type, Object obj, String messagePattern, Object... args) {
    notNull(type, "Type to check against must not be null");
    if (!type.isInstance(obj)) {
        throw new IllegalArgumentException(MessageFormatter.arrayFormat(messagePattern, args).getMessage()
                + " Object of class [" + (obj != null ? obj.getClass().getName() : "null")
                + "] must be an instance of " + type);
    }//from  w w w. j a  v a  2s  . c o  m
}

From source file:com.sunchenbin.store.feilong.core.lang.ClassUtil.java

/**
 * ??./*  w  ww  . j  av a 2 s .  c  o  m*/
 * 
 * <h3>instanceof?/isAssignableFrom/isInstance(Object obj) </h3>
 * 
 * <blockquote>
 * <table border="1" cellspacing="0" cellpadding="4">
 * <tr style="background-color:#ccccff">
 * <th align="left"></th>
 * <th align="left"></th>
 * </tr>
 * <tr valign="top">
 * <td>instanceof?</td>
 * <td>,??????<br>
 * ?oo instanceof TypeName<br>
 * ???,??????<br>
 * instanceofJava?,{@code ==,>,<}?,??,boolean?</td>
 * </tr>
 * <tr valign="top" style="background-color:#eeeeff">
 * <td>isAssignableFrom</td>
 * <td>class,?Class1?Class2????<br>
 * ?Class1.isAssignableFrom(Class2)<br>
 * ?java.lang.Class</td>
 * </tr>
 * <tr valign="top">
 * <td>isInstance(Object obj)</td>
 * <td>obj,objclass? ,true<br>
 * instanceof??</td>
 * </tr>
 * </table>
 * 
 * <p>
 * instanceof :? ----->  <br>
 * isAssignableFrom : -----> ?
 * </p>
 * </blockquote>
 * 
 * @param obj
 *            
 * @param klass
 *            
 * @return  obj , true; if <code>null == klass</code> return false
 * @see java.lang.Class#isInstance(Object)
 */
public static boolean isInstance(Object obj, Class<?> klass) {
    if (null == klass) {
        return false;
    }
    return klass.isInstance(obj);
}

From source file:com.excilys.ebi.bank.util.Asserts.java

public static void isInstanceOf(Class<?> type, Object obj, String messagePattern, Object arg1, Object arg2) {
    notNull(type, "Type to check against must not be null");
    if (!type.isInstance(obj)) {
        throw new IllegalArgumentException(MessageFormatter.format(messagePattern, arg1, arg2).getMessage()
                + " Object of class [" + (obj != null ? obj.getClass().getName() : "null")
                + "] must be an instance of " + type);
    }/*from w w  w .  j a v a2  s .c o  m*/
}

From source file:com.thoughtworks.go.config.BasicEnvironmentConfig.java

private static <T> T as(Class<T> clazz, Object o) {
    if (clazz.isInstance(o)) {
        return clazz.cast(o);
    }/*from   w w w .  j  a va 2 s .  co m*/
    return null;
}

From source file:mondrian.xmla.impl.Olap4jXmlaServlet.java

/**
 * Unwraps a given interface from a given connection.
 *
 * @param connection Connection object// w  w w .  ja  va  2s .co m
 * @param clazz Interface to unwrap
 * @param <T> Type of interface
 * @return Unwrapped object; never null
 * @throws java.sql.SQLException if cannot convert
 */
private static <T> T unwrap(Connection connection, Class<T> clazz) throws SQLException {
    // Invoke Wrapper.unwrap(). Works for JDK 1.6 and later, but we use
    // reflection so that it compiles on JDK 1.5.
    try {
        final Class<?> wrapperClass = Class.forName("java.sql.Wrapper");
        if (wrapperClass.isInstance(connection)) {
            Method unwrapMethod = wrapperClass.getMethod("unwrap");
            return clazz.cast(unwrapMethod.invoke(connection, clazz));
        }
    } catch (ClassNotFoundException e) {
        // ignore
    } catch (NoSuchMethodException e) {
        // ignore
    } catch (InvocationTargetException e) {
        // ignore
    } catch (IllegalAccessException e) {
        // ignore
    }
    if (connection instanceof OlapWrapper) {
        OlapWrapper olapWrapper = (OlapWrapper) connection;
        return olapWrapper.unwrap(clazz);
    }
    throw new SQLException("not an instance");
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Converts a string to an object of a particular class.
 *//*from   w  w w  .j a  v a2 s  .c o m*/
private static Object convert(final Class toClass, final String value) throws Exception {
    if (value == null) {
        return null;
    }
    if (toClass.isInstance(value)) {
        return value;
    }
    if (toClass == Long.class || toClass == Long.TYPE) {
        return Long.decode(value);
    }
    if (toClass == Integer.class || toClass == Integer.TYPE) {
        return Integer.decode(value);
    }
    if (toClass == Boolean.class || toClass == Boolean.TYPE) {
        return Boolean.valueOf(value);
    }
    throw new Exception("Cannot convert attribute value to class " + toClass.getName());
}

From source file:com.l2jfree.util.Introspection.java

private static boolean writeFields(Class<?> c, Object accessor, StringBuilder dest, String eol, boolean init) {
    if (c == null)
        throw new IllegalArgumentException("No class specified.");
    else if (!c.isInstance(accessor))
        throw new IllegalArgumentException(accessor + " is not a " + c.getCanonicalName());
    for (Field f : c.getDeclaredFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod))
            continue;
        if (init)
            init = false;//  w  w  w .j  a  v  a2  s .  c  o  m
        else if (eol == null)
            dest.append(", ");
        String fieldName = null;
        final Column column = f.getAnnotation(Column.class);
        if (column != null)
            fieldName = column.name();
        if (StringUtils.isEmpty(fieldName))
            fieldName = f.getName();
        dest.append(fieldName);
        dest.append(" = ");
        try {
            f.setAccessible(true);
            Object val = f.get(accessor);
            if (accessor == val)
                dest.append("this");
            else
                deepToString(val, dest, null);
        } catch (Exception e) {
            dest.append("???");
        } finally {
            try {
                f.setAccessible(false);
            } catch (Exception e) {
                // ignore
            }
        }
        if (eol != null)
            dest.append(eol);
    }
    return !init;
}

From source file:com.maxleap.utils.Assert.java

/**
 * Assert that the provided object is an instance of the provided class.
 * <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
 * @param type the type to check against
 * @param obj the object to check//from   w  w w .jav  a  2s .  c  o  m
 * @param message a message which will be prepended to the message produced by
 * the function itself, and which may be used to provide context. It should
 * normally end in a ": " or ". " so that the function generate message looks
 * ok when prepended to it.
 * @throws IllegalArgumentException if the object is not an instance of clazz
 * @see Class#isInstance
 */
public static void isInstanceOf(Class type, Object obj, String message) {
    notNull(type, "Type to check against must not be null");
    if (!type.isInstance(obj)) {
        throw new IllegalArgumentException(message + ". Object of class ["
                + (obj != null ? obj.getClass().getName() : "null") + "] must be an instance of " + type);
    }
}

From source file:NumberUtils.java

/**
 * Convert the given number into an instance of the given target class.
 * @param number the number to convert/*from  w ww.j  a  v  a  2 s. c  o m*/
 * @param targetClass the target class to convert to
 * @return the converted number
 * @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 {

    //   Assert.notNull(number, "Number must not be null");
    //   Assert.notNull(targetClass, "Target class must not be null");

    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 new Byte(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 new Short(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 new Integer(number.intValue());
    } else if (targetClass.equals(Long.class)) {
        return new Long(number.longValue());
    } else if (targetClass.equals(Float.class)) {
        return new Float(number.floatValue());
    } else if (targetClass.equals(Double.class)) {
        return new Double(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() + "]");
    }
}

From source file:eu.eidas.node.utils.EidasNodeErrorUtil.java

private static boolean isSAMLEngineException(Throwable e) {
    for (Class t : samlEngineException) {
        if (t.isInstance(e)) {
            return true;
        }//from ww  w.  jav  a2 s  .com
    }
    return false;
}