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:io.stallion.reflection.PropertyUtils.java

/**
 * Try to transform the passed in value into the destinationClass, via a applying a boatload of
 * heuristics./*from  www . ja v  a 2 s .  co  m*/
 *
 * @param value
 * @param destinationClass
 * @return
 */
public static Object transform(Object value, Class destinationClass) {
    if (value == null) {
        return null;
    }
    if (value.getClass() == destinationClass)
        return value;
    if (destinationClass.isInstance(value)) {
        return value;
    }

    // If target type is Date and json was a long, convert the long to a date
    if (destinationClass == Date.class && (value.getClass() == long.class || value.getClass() == Long.class)) {
        return new Date((long) value);
    }
    // Convert integers to longs, if target type is long
    if ((destinationClass == Long.class || destinationClass == long.class)
            && (value.getClass() == int.class || value.getClass() == Integer.class)) {
        return new Long((int) value);
    }
    // Convert ints and longs to ZonedDateTime, if ZonedDateTime was a long
    if (destinationClass == ZonedDateTime.class
            && (value.getClass() == long.class || value.getClass() == Long.class
                    || value.getClass() == int.class || value.getClass() == Integer.class)) {
        if (value.getClass() == Integer.class || value.getClass() == int.class) {
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli(((int) value) * 1000), GeneralUtils.UTC);
        } else {
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli((long) value), GeneralUtils.UTC);
        }
    }

    if (destinationClass == ZonedDateTime.class && value instanceof Timestamp) {
        return ZonedDateTime.ofInstant(((Timestamp) value).toInstant(), UTC);
    }
    if (destinationClass == Long.class && value instanceof BigInteger) {
        return ((BigInteger) value).longValue();
    }

    if (destinationClass == ZonedDateTime.class
            && (value.getClass() == double.class || value.getClass() == Double.class)) {
        return ZonedDateTime.ofInstant(Instant.ofEpochMilli(Math.round((Double) value)), GeneralUtils.UTC);
    }

    // Convert Strings to Enums, if target type was an enum
    if (destinationClass.isEnum()) {
        return Enum.valueOf(destinationClass, value.toString());
    }

    if ((destinationClass == boolean.class || destinationClass == Boolean.class)) {
        if (value instanceof String) {
            return Boolean.valueOf((String) value);
        } else if (value instanceof Integer) {
            return (Integer) value > 0;
        } else if (value instanceof Long) {
            return (Long) value > 0;
        }
    }

    if ((destinationClass == byte.class || destinationClass == Byte.class)
            && value.getClass() == String.class) {
        return new Byte((String) value);
    }
    if ((destinationClass == short.class || destinationClass == Short.class)
            && value.getClass() == String.class) {
        return new Short((String) value);
    }
    if ((destinationClass == int.class || destinationClass == Integer.class)
            && value.getClass() == String.class) {
        return new Integer((String) value);
    }
    if ((destinationClass == long.class || destinationClass == Long.class)
            && value.getClass() == String.class) {
        return new Long((String) value);
    }
    if ((destinationClass == long.class || destinationClass == Long.class) && value instanceof Integer) {
        return new Long((Integer) value);
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == String.class) {
        return new Float((String) value);
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Integer.class) {
        return ((Integer) value).floatValue();
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Long.class) {
        return ((Long) value).floatValue();
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Double.class) {
        return ((Double) value).floatValue();
    }

    if ((destinationClass == double.class || destinationClass == Double.class)
            && value.getClass() == Long.class) {
        return ((Long) value).floatValue();
    }

    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == String.class) {
        return new Float((String) value);
    }

    if ((destinationClass == double.class || destinationClass == Double.class)
            && value.getClass() == String.class) {
        return new Double((String) value);
    }

    // If the type mis-match is due to boxing, just return the value
    if (value.getClass() == boolean.class || value.getClass() == Boolean.class || value.getClass() == byte.class
            || value.getClass() == Byte.class || value.getClass() == short.class
            || value.getClass() == Short.class || value.getClass() == int.class
            || value.getClass() == Integer.class || value.getClass() == long.class
            || value.getClass() == Long.class || value.getClass() == float.class
            || value.getClass() == Float.class || value.getClass() == double.class
            || value.getClass() == Double.class)
        return value;

    throw new PropertyException("cannot convert values of type '" + value.getClass().getName() + "' into type '"
            + destinationClass + "'");
}

From source file:Main.java

private static ArrayList<ArrayList> sortObjectArrayListSimpleMaster(ArrayList listIn, String paramName) {
    ArrayList<ArrayList> answer = new ArrayList<ArrayList>();
    ArrayList newList = new ArrayList();
    ArrayList<Integer> indices = new ArrayList<Integer>();
    try {/*from w w  w .  ja  v  a 2 s  .  co m*/
        if (listIn.size() > 0) {
            Class<?> c = listIn.get(0).getClass();
            Field f = c.getDeclaredField(paramName);
            f.setAccessible(true);
            Class<?> t = f.getType();
            Double dd = new Double(14);
            Float ff = new Float(14);
            Integer ii = new Integer(14);
            Map sortedPos = new LinkedHashMap();
            Map sortedNeg = new LinkedHashMap();
            Map unsorted = new LinkedHashMap();
            int indexCount = 0;
            long count = 0;
            if (t.isPrimitive()) {
                for (Object thisObj : listIn) {
                    Object o = f.get(thisObj);
                    double d = 0;
                    if (t.getName().equals("char")) {
                        d = (int) ((Character) o);
                    } else if (t.isInstance(dd))
                        d = (Double) o;
                    else if (t.isInstance(ff))
                        d = (Float) o;
                    else if (t.isInstance(ii))
                        d = (Integer) o;
                    else
                        d = new Double(o.toString());

                    boolean isNegative = false;

                    if (d < 0) {
                        isNegative = true;
                        d = Math.abs(d);
                    }

                    String format = "%1$30f";
                    String newKey = String.format(format, d);
                    String format2 = "%1$20d";
                    String countString = String.format(format2, count);
                    newKey += "-" + countString;
                    if (isNegative) {
                        sortedNeg.put(newKey, thisObj);
                    } else {
                        sortedPos.put(newKey, thisObj);
                    }
                    unsorted.put(thisObj, indexCount);
                    count++;
                    indexCount++;
                }
                TreeMap<String, Object> resultPos = new TreeMap();
                resultPos.putAll(sortedPos);
                sortedPos = resultPos;
                TreeMap<String, Object> resultNeg = new TreeMap();
                resultNeg.putAll(sortedNeg);
                sortedNeg = resultNeg;
            } else if (t.isInstance(paramName)) {
                // System.out.println("is a string with value " + o);
                for (Object thisObj : listIn) {
                    String key = (String) (f.get(thisObj));
                    sortedPos.put(key + "-" + count, thisObj);
                    unsorted.put(thisObj, indexCount);
                    count++;
                    indexCount++;
                }
                TreeMap<String, Object> result = new TreeMap(String.CASE_INSENSITIVE_ORDER);
                result.putAll(sortedPos);
                sortedPos = result;
            }

            Iterator itNeg = sortedNeg.entrySet().iterator();
            while (itNeg.hasNext()) {
                Map.Entry pairs = (Map.Entry) itNeg.next();
                newList.add(pairs.getValue());
                itNeg.remove();
            }

            Collections.reverse(newList);

            Iterator itPos = sortedPos.entrySet().iterator();
            while (itPos.hasNext()) {
                Map.Entry pairs = (Map.Entry) itPos.next();
                Object obj = pairs.getValue();
                newList.add(obj);
                indices.add((Integer) unsorted.get(obj));
                itPos.remove();
            }
        }
    } catch (Exception e) {
        System.out
                .println("problem sorting list.  listIn.size(): " + listIn.size() + " and param: " + paramName);
        answer.add(newList);
        answer.add(indices);
        return answer;
    }
    answer.add(newList);
    answer.add(indices);
    return answer;
}

From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java

public static <T> T loadConfiguration(InputStream inputStream, Class<? extends T> configurationClass)
        throws Exception {
    if (configurationClass == null) {
        return null;
    }/*from ww  w . j av  a2  s.c o m*/
    Object configuration;
    String configurationPackage = configurationClass.getPackage().getName();
    JAXBContext jaxbContext = JAXBContext.newInstance(configurationPackage);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    configuration = unmarshaller.unmarshal(inputStream);
    if (!configurationClass.isInstance(configuration)) {
        logger.error("Invalid configuration: expected " + configurationClass + ", got " + configuration);
        return null;
    }
    Injections.inject(configuration, ElementsThreadLocals.getServletContext(),
            ElementsThreadLocals.getHttpServletRequest());
    if (configuration instanceof PageActionConfiguration) {
        ((PageActionConfiguration) configuration).init();
    }
    return (T) configuration;
}

From source file:backtype.storm.utils.Utils.java

public static boolean exceptionCauseIsInstanceOf(Class klass, Throwable throwable) {
    Throwable t = throwable;/*from w  w  w  . j av  a  2  s . c  o m*/
    while (t != null) {
        if (klass.isInstance(t)) {
            return true;
        }
        t = t.getCause();
    }
    return false;
}

From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.JobcopyBuilder.java

/**
 * Reimplementation of {@link Jenkins#getItem(String, ItemGroup, Class)}
 * /*from   www.  j  a v a  2 s .  c  o m*/
 * Existing implementation has following problems:
 * * Falls back to {@link Jenkins#getItemByFullName(String)}
 * * Cannot get {@link ItemGroup}
 * 
 * @param pathName
 * @param context
 * @param klass
 * @return
 */
public static <T> T getRelative(String pathName, ItemGroup<?> context, Class<T> klass) {
    if (context == null) {
        context = Jenkins.getInstance().getItemGroup();
    }
    if (pathName == null) {
        return null;
    }

    if (pathName.startsWith("/")) {
        // absolute
        Item item = Jenkins.getInstance().getItemByFullName(pathName);
        return klass.isInstance(item) ? klass.cast(item) : null;
    }

    Object/*Item|ItemGroup*/ ctx = context;

    StringTokenizer tokens = new StringTokenizer(pathName, "/");
    while (tokens.hasMoreTokens()) {
        String s = tokens.nextToken();
        if (s.equals("..")) {
            if (!(ctx instanceof Item)) {
                // can't go up further
                return null;
            }
            ctx = ((Item) ctx).getParent();
            continue;
        }
        if (s.equals(".")) {
            continue;
        }

        if (!(ctx instanceof ItemGroup)) {
            return null;
        }
        ItemGroup<?> g = (ItemGroup<?>) ctx;
        Item i = g.getItem(s);
        if (i == null || !i.hasPermission(Item.READ)) {
            return null;
        }
        ctx = i;
    }

    return klass.isInstance(ctx) ? klass.cast(ctx) : null;
}

From source file:com.springframework.core.annotation.AnnotationUtils.java

/**
 * Get a single {@link Annotation} of {@code annotationType} from the supplied
 * annotation: either the given annotation itself or a direct meta-annotation
 * thereof.//from   w ww  .ja  v  a2s.c  o  m
 * <p>Note that this method supports only a single level of meta-annotations.
 * For support for arbitrary levels of meta-annotations, use one of the
 * {@code find*()} methods instead.
 * @param ann the Annotation to check
 * @param annotationType the annotation type to look for, both locally and as a meta-annotation
 * @return the matching annotation, or {@code null} if not found
 * @since 4.0
 */
@SuppressWarnings("unchecked")
public static <A extends Annotation> A getAnnotation(Annotation ann, Class<A> annotationType) {
    if (annotationType.isInstance(ann)) {
        return (A) ann;
    }
    try {
        return ann.annotationType().getAnnotation(annotationType);
    } catch (Exception ex) {
        // Assuming nested Class values not resolvable within annotation attributes...
        logIntrospectionFailure(ann.annotationType(), ex);
        return null;
    }
}

From source file:com.amalto.webapp.core.util.Util.java

public static boolean causeIs(Throwable throwable, Class<?> cls) {
    Throwable currentCause = throwable;
    while (currentCause != null) {
        if (cls.isInstance(currentCause)) {
            return true;
        }/*from   w  ww . j a v a2  s.  c om*/
        currentCause = currentCause.getCause();
    }
    return false;
}

From source file:com.amalto.webapp.core.util.Util.java

public static <T> T cause(Throwable throwable, Class<T> cls) {
    Throwable currentCause = throwable;
    while (currentCause != null) {
        if (cls.isInstance(currentCause)) {
            return (T) currentCause;
        }//from www. j  a  va 2  s  .  c o m
        currentCause = currentCause.getCause();
    }
    return null;
}

From source file:org.crazydog.util.spring.ObjectUtils.java

/**
 * Check whether the given exception is compatible with the specified
 * exception types, as declared in a throws clause.
 * @param ex the exception to check/*from  ww  w . ja v a 2  s  .c om*/
 * @param declaredExceptions the exception types declared in the throws clause
 * @return whether the given exception is compatible
 */
public static boolean isCompatibleWithThrowsClause(Throwable ex, Class<?>... declaredExceptions) {
    if (!isCheckedException(ex)) {
        return true;
    }
    if (declaredExceptions != null) {
        for (Class<?> declaredException : declaredExceptions) {
            if (declaredException.isInstance(ex)) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.opoopress.maven.plugins.plugin.AbstractDeployMojo.java

private static void configureScpWagonIfRequired(Wagon wagon, Log log) {
    log.debug("configureScpWagonIfRequired: " + wagon.getClass().getName());

    if (System.console() == null) {
        log.debug("No System.console(), skip configure Wagon");
        return;//w w  w. ja v a2s.  c  om
    }

    ClassLoader parent = Thread.currentThread().getContextClassLoader();
    if (parent == null) {
        parent = AbstractDeployMojo.class.getClassLoader();
    }
    List<ClassLoader> loaders = new ArrayList<ClassLoader>();
    loaders.add(wagon.getClass().getClassLoader());
    ChainingClassLoader loader = new ChainingClassLoader(parent, loaders);

    Class<?> scpWagonClass;
    try {
        scpWagonClass = ClassUtils.getClass(loader, "org.apache.maven.wagon.providers.ssh.jsch.ScpWagon");
    } catch (ClassNotFoundException e) {
        log.debug(
                "Class 'org.apache.maven.wagon.providers.ssh.jsch.ScpWagon' not found, skip configure Wagon.");
        return;
    }

    //is ScpWagon
    if (scpWagonClass.isInstance(wagon)) {
        try {
            Class<?> userInfoClass = ClassUtils.getClass(loader,
                    "com.opoopress.maven.plugins.plugin.ssh.SystemConsoleInteractiveUserInfo");
            Object userInfo = userInfoClass.newInstance();
            MethodUtils.invokeMethod(wagon, "setInteractiveUserInfo", userInfo);
            log.debug("ScpWagon using SystemConsoleInteractiveUserInfo(Java 6+).");
        } catch (ClassNotFoundException e) {
            log.debug(
                    "Class 'com.opoopress.maven.plugins.plugin.ssh.SystemConsoleInteractiveUserInfo' not found, skip configure Wagon.");
        } catch (InstantiationException e) {
            log.debug("Instantiate class exception", e);
        } catch (IllegalAccessException e) {
            log.debug(e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            log.debug(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            log.debug(e.getMessage(), e);
        }
    } else {
        log.debug("Not a ScpWagon.");
    }
}