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.l2jfree.gameserver.templates.StatsSet.java

/**
 * Returns an enumeration of <T> from the set
 * /*from   w  w  w. java 2 s . co m*/
 * @param <T> : Class of the enumeration returned
 * @param name : String designating the key in the set
 * @param enumClass : Class designating the class of the value associated with the key in the set
 * @return Enum<T>
 */
@SuppressWarnings("unchecked")
public final <T extends Enum<T>> T getEnum(String name, Class<T> enumClass) {
    Object val = get(name);
    if (val == null)
        throw new IllegalArgumentException(
                "Enum value of type " + enumClass.getName() + " required, but not specified");
    if (enumClass.isInstance(val))
        return (T) val;
    try {
        return Enum.valueOf(enumClass, String.valueOf(val));
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Enum value of type " + enumClass.getName() + "required, but found: " + val);
    }
}

From source file:org.carewebframework.shell.plugins.PluginDefinition.java

/**
 * Returns the list of plugin resources belonging to the specified resource class. Never null.
 * /*from   w w  w.  ja va  2s .  co m*/
 * @param <E> A subclass of PluginResource.
 * @param clazz The resource class being sought.
 * @return List of associated resources.
 */
@SuppressWarnings("unchecked")
public <E extends IPluginResource> List<E> getResources(Class<E> clazz) {
    List<E> list = new ArrayList<E>();

    for (IPluginResource resource : resources) {
        if (clazz.isInstance(resource)) {
            list.add((E) resource);
        }
    }

    return list;
}

From source file:hudson.model.AutoCompletionCandidates.java

/**
 * Auto-completes possible job names./*from   w w w.j av a 2s. c o m*/
 *
 * @param type
 *      Limit the auto-completion to the subtype of this type.
 * @param value
 *      The value the user has typed in. Matched as a prefix.
 * @param container
 *      The nearby contextual {@link ItemGroup} to resolve relative job names from.
 * @since 1.553
 */
public static <T extends Item> AutoCompletionCandidates ofJobNames(final Class<T> type, final String value,
        ItemGroup container) {
    final AutoCompletionCandidates candidates = new AutoCompletionCandidates();
    class Visitor extends ItemVisitor {
        String prefix;

        Visitor(String prefix) {
            this.prefix = prefix;
        }

        @Override
        public void onItem(Item i) {
            String itemName = contextualNameOf(i);

            //Check user's setting on whether to do case sensitive comparison, configured in user -> configure
            //This is the same setting that is used by the global search field, should be consistent throughout
            //the whole application.
            boolean caseInsensitive = UserSearchProperty.isCaseInsensitive();

            if ((startsWithImpl(itemName, value, caseInsensitive)
                    || startsWithImpl(value, itemName, caseInsensitive))
                    // 'foobar' is a valid candidate if the current value is 'foo'.
                    // Also, we need to visit 'foo' if the current value is 'foo/bar'
                    && (value.length() > itemName.length() || !itemName.substring(value.length()).contains("/"))
                    // but 'foobar/zot' isn't if the current value is 'foo'
                    // we'll first show 'foobar' and then wait for the user to type '/' to show the rest
                    && i.hasPermission(Item.READ)
            // and read permission required
            ) {
                if (type.isInstance(i) && startsWithImpl(itemName, value, caseInsensitive))
                    candidates.add(itemName);

                // recurse
                String oldPrefix = prefix;
                prefix = itemName;
                super.onItem(i);
                prefix = oldPrefix;
            }
        }

        private String contextualNameOf(Item i) {
            if (prefix.endsWith("/") || prefix.length() == 0)
                return prefix + i.getName();
            else
                return prefix + '/' + i.getName();
        }
    }

    if (container == null || container == Jenkins.getInstance()) {
        new Visitor("").onItemGroup(Jenkins.getInstance());
    } else {
        new Visitor("").onItemGroup(container);
        if (value.startsWith("/"))
            new Visitor("/").onItemGroup(Jenkins.getInstance());

        for (String p = "../"; value.startsWith(p); p += "../") {
            container = ((Item) container).getParent();
            new Visitor(p).onItemGroup(container);
        }
    }

    return candidates;
}

From source file:com.eryansky.common.excel.ExportExcel.java

private HSSFWorkbook exportExcelInUserModel2File(String title, Class<T> pojoClass, Collection<T> dataSet) {
    // /*from   ww w  . ja va 2  s .  c o m*/
    HSSFWorkbook workbook = null;
    try {
        // 
        workbook = new HSSFWorkbook();
        // ?
        Sheet sheet = workbook.createSheet(title);

        // 
        List<String> exportFieldTitle = new ArrayList<String>();
        List<Integer> exportFieldWidth = new ArrayList<Integer>();
        // ???get
        List<Method> methodObj = new ArrayList<Method>();
        Map<String, Method> convertMethod = new HashMap<String, Method>();
        Class superClazz = null;
        Field fileds[] = new Field[0];
        boolean flag = true;
        while (flag) {
            if (superClazz != null) {
                superClazz = superClazz.getSuperclass();
            } else {
                superClazz = pojoClass.getSuperclass();
            }
            if (superClazz.isInstance(Object.class)) {
                flag = false;
            } else {
                Field[] sf = superClazz.getDeclaredFields();
                if (sf != null && sf.length > 0) {
                    for (int m = 0; m < sf.length; m++) {
                        fileds = ArrayUtils.addAll(fileds, sf[m]);
                    }
                }
            }

        }
        // 
        Field cfileds[] = pojoClass.getDeclaredFields();
        if (cfileds != null && cfileds.length > 0) {
            for (int n = 0; n < cfileds.length; n++) {
                fileds = ArrayUtils.addAll(fileds, cfileds[n]);
            }
        }
        // ??filed
        for (int i = 0; i < fileds.length; i++) {
            Field field = fileds[i];
            Excel excel = field.getAnnotation(Excel.class);
            // annottion
            if (excel != null) {
                // 
                exportFieldTitle.add(excel.exportName());
                // 
                exportFieldWidth.add(excel.exportFieldWidth());
                // ?
                String fieldname = field.getName();
                // System.out.println(i+""+excel.exportName()+" "+excel.exportFieldWidth());
                StringBuffer getMethodName = new StringBuffer("get");
                getMethodName.append(fieldname.substring(0, 1).toUpperCase());
                getMethodName.append(fieldname.substring(1));

                Method getMethod = pojoClass.getMethod(getMethodName.toString(), new Class[] {});

                methodObj.add(getMethod);
                if (excel.exportConvert() == true) {
                    //----------------------------------------------------------------
                    //update-begin--Author:Quainty  Date:20130524 for[8]excel
                    // get/setXxxxConvert??? ?Entity?
                    StringBuffer getConvertMethodName = new StringBuffer("convertGet");
                    getConvertMethodName.append(fieldname.substring(0, 1).toUpperCase());
                    getConvertMethodName.append(fieldname.substring(1));
                    //getConvertMethodName.append("Convert");
                    //update-end--Author:Quainty  Date:20130524 for[8]excel
                    //----------------------------------------------------------------
                    // System.out.println("convert: "+getConvertMethodName.toString());
                    Method getConvertMethod = pojoClass.getMethod(getConvertMethodName.toString(),
                            new Class[] {});
                    convertMethod.put(getMethodName.toString(), getConvertMethod);
                }
            }
        }
        int index = 0;
        // 
        Row row = sheet.createRow(index);
        row.setHeight((short) 450);
        CellStyle titleStyle = getTitleStyle(workbook);
        for (int i = 0, exportFieldTitleSize = exportFieldTitle.size(); i < exportFieldTitleSize; i++) {
            Cell cell = row.createCell(i);
            // cell.setCellStyle(style);
            RichTextString text = new HSSFRichTextString(exportFieldTitle.get(i));
            cell.setCellValue(text);
            cell.setCellStyle(titleStyle);
        }

        // ?
        for (int i = 0; i < exportFieldWidth.size(); i++) {
            // 256=65280/255
            sheet.setColumnWidth(i, 256 * exportFieldWidth.get(i));
        }
        Iterator its = dataSet.iterator();
        // ??
        while (its.hasNext()) {
            // 
            index++;
            row = sheet.createRow(index);
            row.setHeight((short) 350);
            Object t = its.next();
            for (int k = 0, methodObjSize = methodObj.size(); k < methodObjSize; k++) {
                Cell cell = row.createCell(k);
                Method getMethod = methodObj.get(k);
                Object value = null;
                if (convertMethod.containsKey(getMethod.getName())) {
                    Method cm = convertMethod.get(getMethod.getName());
                    value = cm.invoke(t, new Object[] {});
                } else {
                    value = getMethod.invoke(t, new Object[] {});
                }
                cell.setCellValue(value == null ? "" : value.toString());

                if (index % 2 == 0)
                    cell.setCellStyle(getTwoStyle(workbook));
                else
                    cell.setCellStyle(getOneStyle(workbook));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return workbook;
}

From source file:com.vmware.identity.sts.ws.SignatureValidator.java

/**
 * Evaluates if the provided list contains a single instance of a JAXBElement
 * which is of the given type/*from  w  w  w .  jav  a 2  s . co m*/
 *
 * @param list
 * @param valueType
 * @return
 */
@SuppressWarnings("unchecked")
private <T> T getTheValue(List<?> list, Class<T> valueType, FaultKey key, String cause) {

    if (list == null) {
        throw new WSFaultException(key, cause);
    }

    JAXBElement<?> theOnlyElement = getSingleJaxbElement(list);
    if (theOnlyElement == null || !valueType.isInstance(theOnlyElement.getValue())) {
        throw new WSFaultException(key, cause);
    }
    return (T) theOnlyElement.getValue();
}

From source file:org.echocat.jomon.spring.ContextLoadThreadGroup.java

public <T extends Throwable> void throwOn(@Nonnull Class<T> allowedThrowableType) throws T {
    synchronized (_failedThreads) {
        final Throwable highestRatedThrowable = findHighestRatedThrowableIn(_failedThreads);
        if (highestRatedThrowable != null) {
            for (final List<Throwable> throwables : _failedThreads.values()) {
                for (final Throwable throwable : throwables) {
                    if (!highestRatedThrowable.equals(throwable)) {
                        highestRatedThrowable.addSuppressed(throwable);
                    }/*  ww  w .  j a  v  a2 s. c  om*/
                }
            }
            if (allowedThrowableType.isInstance(highestRatedThrowable)) {
                throw allowedThrowableType.cast(highestRatedThrowable);
            } else if (highestRatedThrowable instanceof RuntimeException) {
                throw (RuntimeException) highestRatedThrowable;
            } else if (highestRatedThrowable instanceof Error) {
                throw (Error) highestRatedThrowable;
            } else {
                throw new RuntimeException(highestRatedThrowable);
            }
        }
    }
}

From source file:com.francetelecom.clara.cloud.logicalmodel.ProcessingNode.java

/**
 * List the Logical Services of a specific class.
 * <p>//from  ww w.  j a  v a2 s.  co m
 * Retrieves all {@link LogicalService} that is connected to the current ExecNode through the {@link LogicalNodeServiceAssociation}
 *
 * @param filteredClass The class of the logicalService to restrict to (e.g. LogicalWebGUIService.class), or null
 *                      to not perform any filtering. Note this may be a superclass or an implementing interface.
 * @return a non-null, possibly empty list
 */
public <E extends LogicalService> List<E> listLogicalServices(Class<E> filteredClass) {
    List<E> services = new ArrayList<E>();
    for (LogicalNodeServiceAssociation association : this.logicalNodeServiceAssociations) {
        LogicalService logicalService = association.logicalService;
        boolean includeThisClass = false;
        if (filteredClass == null) {
            includeThisClass = true;
        } else {
            includeThisClass = (filteredClass.isInstance(logicalService));
        }
        if (includeThisClass) {
            services.add((E) logicalService);
        }
    }

    return Collections.unmodifiableList(services);
}

From source file:org.mulgara.scon.Connection.java

@SuppressWarnings("unchecked")
@Override/* w ww.  j a va  2 s.  co  m*/
public <T> T unwrap(Class<T> iface) throws SQLException {
    if (iface.isInstance(this))
        return (T) this;
    throw new SQLException("scon does not implement: " + iface.getName());
}

From source file:com.l2jfree.gameserver.datatables.ItemTable.java

public <T extends L2Item> T getTemplate(int id, Class<T> clazz) {
    L2Item item = getTemplate(id);//  ww w  . j  a v  a2 s  .  c om

    if (clazz.isInstance(item))
        return clazz.cast(item);
    else
        return null;
}

From source file:com.medvision360.medrecord.engine.ArchetypeBasedValidator.java

private boolean instanceOf(Object value, String rmEntity) {
    if (value == null || rmEntity == null) {
        return value == null && rmEntity == null;
    }//w  w  w. jav a 2s . c om

    rmEntity = toClassName(rmEntity);
    String valueClassStr = value.getClass().getSimpleName();
    if (valueClassStr.equals(rmEntity)) {
        return true;
    }
    Class<?> rmType;
    try {
        rmType = retrieveRMType(rmEntity);
    } catch (RMObjectBuildingException e) {
        return false;
    }

    return rmType.isInstance(value);
}