Example usage for java.lang Class cast

List of usage examples for java.lang Class cast

Introduction

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

Prototype

@SuppressWarnings("unchecked")
@HotSpotIntrinsicCandidate
public T cast(Object obj) 

Source Link

Document

Casts an object to the class or interface represented by this Class object.

Usage

From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.DatareportsServiceImpl.java

@Cached
public Map<String, Comparator> getComparatorMap(final Class clazz, final Map<String, String> colMap) {
    final Map<String, Comparator> compMap = new HashMap<String, Comparator>();
    final Comparator alphaNum = new AlphanumComparator();
    for (final Map.Entry<String, String> entry : colMap.entrySet()) {
        compMap.put(entry.getKey(), new Comparator() {
            public int compare(final Object o1, final Object o2) {
                try {
                    final Method getter = GetterMethod.getGetter(clazz, entry.getKey());
                    final Object obj1 = getter.invoke(clazz.cast(o1));
                    final Object obj2 = getter.invoke(clazz.cast(o2));
                    final String str1 = obj1 == null ? "" : obj1.toString();
                    final String str2 = obj2 == null ? "" : obj2.toString();
                    if (str1 == null || str2 == null) {
                        return 0;
                    }//from  ww w  .  j a  va2s  . c  o m
                    return alphaNum.compare(str1.toUpperCase(), str2.toUpperCase());
                } catch (Exception e) {
                    logger.debug(FancyExceptionLogger.printException(e));
                    return 0;
                }
            }
        });
    }
    return compMap;
}

From source file:com.delphix.session.module.rmi.impl.RmiFactoryImpl.java

@Override
public RmiProtocolServer createServer() {
    return createServer(new ObjectCreator() {

        @Override//from   w ww .  j  ava 2 s.  c  o  m
        public <T> T create(Class<T> type) {
            String[] names = context.getBeanNamesForType(type);
            if (names.length == 0) {
                throw new RuntimeException("there is no spring bean of type " + type.getCanonicalName());
            } else if (names.length > 1) {
                throw new RuntimeException(
                        "there is more than one spring bean of type " + type.getCanonicalName());
            }

            if (!context.isPrototype(names[0])) {
                throw new RuntimeException(String.format("the spring bean '%s' of type '%s' is not a prototype",
                        names[0], type.getCanonicalName()));
            }

            return type.cast(context.getBean(names[0]));
        }
    });
}

From source file:com.blackducksoftware.tools.commonframework.core.config.ConfigurationManager.java

/**
 * Retrieves optional property, if property is missing returns default
 * value.//from  www  .j  a v  a 2  s  . c  o m
 *
 * @param <T>
 * @param key
 * @param defaultValue
 * @return
 * @return
 */
@SuppressWarnings("unchecked")
@Override
public <T> T getOptionalProperty(final String propertyKey, final T defaultValue, final Class<T> theClass) {
    final T classType = theClass.cast(defaultValue);
    String value = null;
    T returnValue = null;

    if (props.containsKey(propertyKey)) {
        String propStr = props.getProperty(propertyKey);

        if (propStr != null) {
            propStr = propStr.trim();
        }

        value = propStr;
    }

    if (value == null) {
        value = defaultValue.toString();
    }

    if (classType instanceof Boolean) {
        returnValue = (T) new Boolean(value);
    } else if (classType instanceof Integer) {
        returnValue = (T) new Integer(value);
    } else {
        returnValue = (T) new String(value);
    }

    return returnValue;
}

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  o m*/

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

From source file:com.rodaxsoft.mailgun.converters.CampaignConverter.java

@Override
public <T> T convert(Class<T> type, Object value) {

    Campaign campaign = null;/*from  ww  w .j  av  a  2  s  . c o  m*/

    if (value instanceof JSONObject) {

        JSONObject json = (JSONObject) value;

        Transformer<String, String> keyTransformer;
        keyTransformer = new KeyTransformer();

        @SuppressWarnings("unchecked")
        final Map<String, Object> copy = new HashMap<>(json);
        Map<String, Object> transformed;
        transformed = TransformedMap.transformedMap(copy, keyTransformer, null);

        campaign = new Campaign();
        try {
            BeanUtils.populate(campaign, transformed);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ContextedRuntimeException(e);
        }
    }

    return type.cast(campaign);
}

From source file:de.taimos.gpsd4java.backend.GPSdEndpoint.java

private <T extends IGPSObject> T syncCommand(final String command, final Class<T> responseClass)
        throws IOException {
    synchronized (this.asyncMutex) {
        this.out.write(command + "\n");
        this.out.flush();
        if (responseClass == WatchObject.class) {
            lastWatch = command;//from   www. jav  a2 s  .  c o  m
        }
        while (true) {
            // wait for awaited message
            final IGPSObject result = this.waitForResult();
            if ((result == null) || result.getClass().equals(responseClass)) {
                return responseClass.cast(result);
            }
        }
    }
}

From source file:com.htmlhifive.sync.resource.AbstractCrudSyncResource.java

/**
 * ???ID???????.// ww  w.ja v a  2  s . c  om
 *
 * @param common ?
 * @return 
 */
private T createDeletedItem(ResourceItemCommonData common) {
    Class<T> itemType = getItemType();

    BeanWrapper deletedWrapper = PropertyAccessorFactory
            .forBeanPropertyAccess(BeanUtils.instantiateClass(itemType));
    deletedWrapper.setPropertyValue(getIdFieldName(), common.getTargetItemId());

    return itemType.cast(deletedWrapper.getWrappedInstance());
}

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);
                    }/*from www  .j  a v  a2s .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:net.camelpe.extension.camel.spi.CdiInjector.java

/**
 * @see org.apache.camel.spi.Injector#newInstance(java.lang.Class,
 *      java.lang.Object)/*from   w  w  w . ja v a2  s  . c om*/
 */
@Override
public <T> T newInstance(final Class<T> type, final Object instance) {
    Validate.notNull(type, "type");
    Validate.notNull(instance, "instance");
    Validate.isTrue(type.isAssignableFrom(instance.getClass()),
            "The supplied instance [" + instance + "] is not an instance of type [" + type.getName() + "]");
    getLog().trace("Creating new configured instance of type = [{}], " + "optionally using instance [{}] ...",
            type.getName(), instance);
    if (isSingleton(instance)) {
        getLog().debug("The supplied type [{}] is annotated to be a singleton: "
                + "returning the supplied instance [{}].", type.getName(), instance);

        return type.cast(instance);
    }
    getLog().debug("The supplied type [{}] is not known to be a singleton: " + "will create a new instance.",
            type.getName());

    return newInstance(type);
}