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:it.cnr.icar.eric.server.query.ReferenceResolverImpl.java

/**
 * Gets the Set of ReferenceInfo for specified reference attribute within RegistryObject.
 *
 * Reference attributes based on scanning rim.xsd for anyURI.
 *
 * @param ro specifies the RegistryObject whose reference attribute is being sought.
 *
 * @param idMap The HashMap with old temporary id to new permanent id mapping.
 *
 *///w  w  w  . j  av  a 2  s.  com
@SuppressWarnings("unchecked")
private void processRefAttribute(ServerRequestContext serverContext, RegistryObjectType ro, String className,
        Map<?, ?> idMap, String attribute, @SuppressWarnings("rawtypes") Collection refObjs)
        throws JAXRException {
    log.trace("start: processRefAttribute");
    try {
        //Use reflections API to get the attribute value, check if it needs to be mapped
        //and set it with mapped value if needed and add the targetObject in refObjs
        Class<?> clazz = Class.forName(className);
        if (!(clazz.isInstance(ro))) {
            return;
        }

        //Get the attribute value by calling get method
        String getMethodName = "get" + attribute;
        Method getMethod = clazz.getMethod(getMethodName, (java.lang.Class[]) null);

        //Invoke getMethod to get the reference target object's id
        String targetObjectId = (String) getMethod.invoke(ro, (java.lang.Object[]) null);

        if (targetObjectId != null) {
            //Check if id has been mapped to a new id
            if (idMap.containsKey(targetObjectId)) {
                //Replace old id with new id
                targetObjectId = (String) idMap.get(targetObjectId);

                //Use set method to set new value on ro
                Class<?>[] parameterTypes = new Class[1];
                Object[] parameterValues = new Object[1];
                parameterTypes[0] = Class.forName("java.lang.String");
                parameterValues[0] = targetObjectId;
                String setMethodName = "set" + attribute;
                Method setMethod = clazz.getMethod(setMethodName, parameterTypes);
                setMethod.invoke(ro, parameterValues);
            }
            log.debug("sourceObject: " + ro.getId() + " targetObject: " + targetObjectId + " attribute: "
                    + attribute);
            RegistryObjectType refObj = QueryManagerFactory.getInstance().getQueryManager()
                    .getRegistryObject(serverContext, targetObjectId);
            if (refObj != null && !refObjs.contains(refObj)) {
                refObjs.add(refObj);
            }
        }

    } catch (Exception e) {
        //throw new OMARExeption("Class = " ro.getClass() + " attribute = " + attribute", e);
        log.error(CommonResourceBundle.getInstance().getString("message.ErrorClassAttribute",
                new Object[] { ro.getClass(), attribute }));
        e.printStackTrace();
    }
    log.trace("end: processRefAttribute");
}

From source file:info.papdt.blacklight.support.Utility.java

public static void setActionBarTranslation(Activity activity, float y) {
    ViewGroup vg = (ViewGroup) activity.findViewById(android.R.id.content).getParent();
    int count = vg.getChildCount();

    if (DEBUG) {/* ww  w . j av  a  2  s .c o m*/
        Log.d(TAG, "==========================");
    }

    // Get the class of action bar
    Class<?> actionBarContainer = null;
    Field isSplit = null;

    try {
        actionBarContainer = Class.forName("com.android.internal.widget.ActionBarContainer");
        isSplit = actionBarContainer.getDeclaredField("mIsSplit");
        isSplit.setAccessible(true);
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    for (int i = 0; i < count; i++) {
        View v = vg.getChildAt(i);

        if (v.getId() != android.R.id.content) {
            if (DEBUG) {
                Log.d(TAG, "Found View: " + v.getClass().getName());
            }

            try {
                if (actionBarContainer.isInstance(v)) {
                    if (DEBUG) {
                        Log.d(TAG, "Found ActionBarContainer");
                    }

                    if (isSplit.getBoolean(v)) {
                        if (DEBUG) {
                            Log.d(TAG, "Found Split Action Bar");
                        }

                        continue;
                    }
                }
            } catch (Exception e) {
                if (DEBUG) {
                    Log.e(TAG, Log.getStackTraceString(e));
                }
            }

            v.setTranslationY(y);
        }
    }

    if (DEBUG) {
        Log.d(TAG, "==========================");
    }
}

From source file:de.unioninvestment.eai.portal.portlet.crud.domain.model.Panel.java

/**
 * Findet das nchste Seiten-Element fr ein bergebenes Seiten-Element.
 * /* w ww.j av  a  2 s .c o  m*/
 * @param pageElementType
 *            Typ des Elementes
 * @param currentElement
 *            aktuelles Element
 * @param <T>
 *            Typ des Elementes
 * 
 * @return das gefundene Element
 */
@SuppressWarnings("unchecked")
public <T extends Component> T findNextElement(Class<T> pageElementType, Component currentElement) {
    int i = currentElement == null ? -1 : indexOf(currentElement);
    if (elements.size() > i + 1) {
        for (Component element : elements.subList(i + 1, elements.size())) {
            if (pageElementType.isInstance(element)) {
                return (T) element;
            }
        }
    }
    return null;
}

From source file:edu.cornell.mannlib.vitro.utilities.containerneutral.CheckContainerNeutrality.java

/**
 * Check that the supplied className can be instantiated with a
 * zero-argument constructor, and assigned to a variable of the target
 * class.// w  ww  .j a  va  2 s .co m
 */
private String confirmClassNameIsValid(String className, Class<?> targetClass) {
    try {
        Class<?> specifiedClass = Class.forName(className);
        Object o = specifiedClass.newInstance();
        if (!targetClass.isInstance(o)) {
            return specifiedClass.getSimpleName() + " is not a subclass of " + targetClass.getSimpleName()
                    + ".";
        }
    } catch (ClassNotFoundException e) {
        return "The class does not exist.";
    } catch (InstantiationException e) {
        return "The class does not have a public constructor " + "that takes zero arguments.";
    } catch (IllegalAccessException e) {
        return "The class does not have a public constructor " + "that takes zero arguments.";
    }
    return null;
}

From source file:com.yahoo.sshd.server.settings.TestOptions.java

@SuppressWarnings("rawtypes")
@Test(dataProvider = "shells")
public void testForwarding(ShellMode shellMode, boolean forwardingAllowed, Class c)
        throws SshdConfigurationException {
    SshdSettingsBuilder builder = new SshdSettingsBuilder(new String[] {});
    builder.setSetShellMode(shellMode);// w w w  . j  av  a2s .c o m

    SshdSettingsInterface settings = builder.build();

    Assert.assertEquals(settings.isForwardingAllowed(), forwardingAllowed);
    Assert.assertTrue(c.isInstance(settings.getForwardingFilter()));
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected boolean isUncaughtException(Throwable e) {
    for (Class<? extends RuntimeException> exception : getUncaughtExceptions()) {
        if (exception.isInstance(e)) {
            if (log.isDebugEnabled()) {
                log.debug("Exception " + e.getClass().getName() + " is uncaught exception (extends "
                        + exception.getName() + ")");
            }/*from w w w.j a v a  2  s .  c o  m*/
            return true;
        }
    }

    return false;
}

From source file:hudson.model.User.java

/**
 * Gets the specific property, or null.//from  ww  w. j  a v  a2 s .  c  o  m
 */
public <T extends UserProperty> T getProperty(Class<T> clazz) {
    for (UserProperty p : properties) {
        if (clazz.isInstance(p))
            return clazz.cast(p);
    }
    return null;
}

From source file:io.fabric8.spring.cloud.kubernetes.reload.ConfigurationChangeDetector.java

/**
 * Finds all registered property sources of the given type.
 *//* ww w. ja  va  2 s  . c o m*/
protected <S extends PropertySource<?>> List<S> findPropertySources(Class<S> sourceClass) {
    List<S> managedSources = new LinkedList<>();

    LinkedList<PropertySource<?>> sources = toLinkedList(environment.getPropertySources());
    while (!sources.isEmpty()) {
        PropertySource<?> source = sources.pop();
        if (source instanceof CompositePropertySource) {
            CompositePropertySource comp = (CompositePropertySource) source;
            sources.addAll(comp.getPropertySources());
        } else if (sourceClass.isInstance(source)) {
            managedSources.add(sourceClass.cast(source));
        }
    }

    return managedSources;
}

From source file:org.ocelotds.core.services.ArgumentConvertorTest.java

/**
 * Test of convertArgument method, of class ArgumentConvertor.
 *//*from   ww  w.  j  a  va2 s  . c o m*/
@Test
public void testConvertArgument() throws IllegalArgumentException {
    System.out.println("convertArgument");
    Iterator<String> args = Arrays.asList("\"toto\"", "5", "[\"a\",\"b\"]", "[[\"a\", \"b\"],[\"c\", \"d\"]]",
            "[\"c\",\"d\"]", "{\"a\":1, \"b\":2, \"c\":3}", "{\"integer\":5}").iterator();
    Type col = new GenericType<Collection<String>>() {
    }.getType();
    Type map = new GenericType<Map<String, Integer>>() {
    }.getType();
    Type colArray = new GenericType<Collection<String[]>>() {
    }.getType();
    Type array = new String[] {}.getClass();
    for (final Type type : new Type[] { String.class, Integer.class, array, colArray, col, map,
            Result.class }) {
        String arg = args.next();
        Object result = instance.convertArgument(arg, type);
        assertThat(result).is(new Condition<Object>("" + type) {
            @Override
            public boolean matches(Object t) {
                Class cls;
                if (type instanceof ParameterizedType) {
                    cls = (Class) ((ParameterizedType) type).getRawType();
                } else {
                    cls = (Class) type;
                }
                return cls.isInstance(t);
            }
        });
    }
}

From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.java

/**
 * ResultSet.getObject() returns an Integer object for an INT column.  The
 * setter method for the property might take an Integer or a primitive int.
 * This method returns true if the value can be successfully passed into
 * the setter method.  Remember, Method.invoke() handles the unwrapping
 * of Integer into an int./*from   ww  w  .java2s. c o  m*/
 *
 * @param value The value to be passed into the setter method.
 * @param type The setter's parameter type (non-null)
 * @return boolean True if the value is compatible (null => true)
 */
private boolean isCompatibleType(Object value, Class<?> type) {
    // Do object check first, then primitives
    if (value == null || type.isInstance(value)) {
        return true;

    } else if (type.equals(Integer.TYPE) && Integer.class.isInstance(value)) {
        return true;

    } else if (type.equals(Long.TYPE) && Long.class.isInstance(value)) {
        return true;

    } else if (type.equals(Double.TYPE) && Double.class.isInstance(value)) {
        return true;

    } else if (type.equals(Float.TYPE) && Float.class.isInstance(value)) {
        return true;

    } else if (type.equals(Short.TYPE) && Short.class.isInstance(value)) {
        return true;

    } else if (type.equals(Byte.TYPE) && Byte.class.isInstance(value)) {
        return true;

    } else if (type.equals(Character.TYPE) && Character.class.isInstance(value)) {
        return true;

    } else if (type.equals(Boolean.TYPE) && Boolean.class.isInstance(value)) {
        return true;

    }
    return false;

}