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:com.linkedin.pinot.common.data.DateTimeFormatSpec.java

/**
 * <ul>//from  ww  w.j  ava 2  s . c  om
 * <li>Given a timestamp in millis, convert it to the given format
 * This method should not do validation of outputGranularity.
 * The validation should be handled by caller using {@link #isValidFormat(String)}</li>
 * <ul>
 * <li>1) given dateTimeColumnValueMS = 1498892400000 and format=1:HOURS:EPOCH,
 * dateTimeSpec.fromMillis(1498892400000) = 416359 (i.e. dateTimeColumnValueMS/(1000*60*60))</li>
 * <li>2) given dateTimeColumnValueMS = 1498892400000 and format=5:MINUTES:EPOCH,
 * dateTimeSpec.fromMillis(1498892400000) = 4996308 (i.e. timeColumnValueMS/(1000*60*5))</li>
 * <li>3) given dateTimeColumnValueMS = 1498892400000 and
 * format=1:DAYS:SIMPLE_DATE_FORMAT:yyyyMMdd, dateTimeSpec.fromMillis(1498892400000) = 20170701</li>
 * </ul>
 * </ul>
 * @param dateTimeColumnValueMS
 * @param toFormat - the format in which to convert the millis value
 * @param type - type of return value (can be int/long or string depending on time format)
 * @return dateTime column value in dateTimeFieldSpec
 */
public <T extends Object> T fromMillisToFormat(Long dateTimeColumnValueMS, Class<T> type) {
    Preconditions.checkNotNull(dateTimeColumnValueMS);

    Object dateTimeColumnValue = null;

    if (_patternSpec.getTimeFormat().equals(TimeFormat.EPOCH)) {
        dateTimeColumnValue = _unitSpec.getTimeUnit().convert(dateTimeColumnValueMS, TimeUnit.MILLISECONDS)
                / _size;
    } else {
        dateTimeColumnValue = _patternSpec.getDateTimeFormatter().print(dateTimeColumnValueMS);
    }
    return type.cast(dateTimeColumnValue);
}

From source file:org.opencb.commons.datastore.core.ObjectMap.java

public <T> T get(final String field, final Class<T> clazz, T defaultValue) {
    if (objectMap.containsKey(field)) {
        Object obj = objectMap.get(field);
        if (clazz.isInstance(obj)) {
            return clazz.cast(obj);
        }//from w  w w.j  a  v a  2 s  . c  om
    }
    return defaultValue;
}

From source file:net.refractions.udig.catalog.internal.shp.ShpServiceImpl.java

public <T> T resolve(Class<T> adaptee, IProgressMonitor monitor) throws IOException {

    if (monitor == null)
        monitor = new NullProgressMonitor();

    if (adaptee == null) {
        throw new NullPointerException("No adaptor specified"); //$NON-NLS-1$
    }/*w  ww  .  j  a  v a 2 s .com*/
    if (adaptee.isAssignableFrom(ShapefileDataStore.class))
        return adaptee.cast(getDS(monitor));
    if (adaptee.isAssignableFrom(File.class))
        return adaptee.cast(toFile());
    return super.resolve(adaptee, monitor);
}

From source file:io.coala.config.AbstractPropertyGetter.java

/**
 * @param valueType/*  w w  w  .  ja  va  2  s .c om*/
 * @return
 * @throws CoalaException if value was not configured nor any default was
 *             set
 */
public <T> T getObject(final Class<T> valueType) throws CoalaRuntimeException {
    if (valueType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("valueType");

    final String value = get();
    try {
        return valueType.cast(ClassUtil.deserialize(value, valueType));
    } catch (final CoalaRuntimeException e) {
        throw e;
    } catch (final Throwable e) {
        throw CoalaExceptionFactory.UNMARSHAL_FAILED.createRuntime(e, value, valueType);
    }
}

From source file:com.eucalyptus.images.Images.java

private static <R, T, TT> Function<T, R> typedFunction(final Function<TT, R> typeSpecificFunction,
        final Class<TT> subClass, @Nullable final R defaultValue) {
    return new Function<T, R>() {
        @Override/*w ww  . j  a  va  2 s.  c o m*/
        public R apply(final T parameter) {
            return subClass.isInstance(parameter) ? typeSpecificFunction.apply(subClass.cast(parameter))
                    : defaultValue;
        }
    };
}

From source file:ch.algotrader.config.spring.DefaultConfigProvider.java

public final <T> T getParameter(final String name, final Class<T> clazz) throws ClassCastException {

    Object param = getRawValue(name);
    if (param == null && this.fallbackProvider != null) {

        param = this.fallbackProvider.getParameter(name, clazz);
    }//  www. j  ava2s  . c o  m
    if (param == null) {

        return null;
    }
    if (param instanceof String && StringUtils.isBlank((String) param)) {

        return null;
    }
    if (this.conversionService.canConvert(param.getClass(), clazz)) {

        return this.conversionService.convert(param, clazz);
    } else {

        // Attempt direct cast as the last resort
        return clazz.cast(param);
    }
}

From source file:com.atlassian.jira.ComponentManager.java

/**
 * Retrieves and returns a component which is an instance of given class.
 * <p>/* w  w w .j  av a 2 s  . c om*/
 * In practise, this is the same as {@link #getComponent(Class)} except it will try to find a unique component that
 * implements/extends the given Class even if the Class is not an actual component key.
 * <p> Please note that this method only gets components from JIRA's core Pico Containter. That is, it retrieves
 * core components and components declared in Plugins1 plugins, but not components declared in Plugins2 plugins.
 * Plugins2 components can be retrieved via the {@link #getOSGiComponentInstanceOfType(Class)} method, but only if
 * they are public.
 *
 * @param clazz class to find a component instance by
 * @return found component
 * @see #getOSGiComponentInstanceOfType(Class)
 * @see PicoContainer#getComponent(Class))
 *
 * @deprecated since 6.0 - please use the jira-api {@link com.atlassian.jira.component.ComponentAccessor#getComponent(Class)} instead
 *
 */
/*
  NOTE to JIRA DEVS : Stop using this method for general purpose component retrieval.  Use ComponentAccessor please.
*/
public static <T> T getComponentInstanceOfType(final Class<T> clazz) {
    // Try fast approach
    T component = getComponent(clazz);
    if (component != null) {
        return component;
    }
    // Look the slow way
    component = clazz.cast(getInstance().getContainer().getComponent(clazz));
    if (component != null) {
        // Lets log this so we know there is a naughty component
        if (log.isDebugEnabled()) {
            // Debug mode - include a stacktrace to find the caller
            try {
                throw new IllegalArgumentException();
            } catch (IllegalArgumentException ex) {
                log.warn("Unable to find component with key '" + clazz + "' - eventually found '" + component
                        + "' the slow way.", ex);
            }
        } else {
            log.warn("Unable to find component with key '" + clazz + "' - eventually found '" + component
                    + "' the slow way.");
        }
    }
    return component;
}

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

public List<Predicate> genListPredicates(final Class clazz, final List<String> valueList, final String getter) {
    List<Predicate> predList = null;
    if (valueList != null) {
        predList = new LinkedList<Predicate>();
        for (final String strValue : valueList) {
            predList.add(new Predicate() {
                public boolean evaluate(Object o) {
                    try {
                        final Method m = GetterMethod.getGetter(clazz, getter);
                        final Object obj = m.invoke(clazz.cast(o));
                        final String str = obj == null ? "" : obj.toString();
                        return strValue.equalsIgnoreCase(str);
                    } catch (Exception e) {
                        logger.debug(FancyExceptionLogger.printException(e));
                        return true;
                    }//from www. j  a  v a2 s. c  o  m
                }
            });
        }
    }
    return predList;
}

From source file:de.drv.dsrv.extra.marshaller.impl.ExtraUnmarschaller.java

@Override
public <X> X unmarshal(final Source source, final Class<X> extraTransportClass, final boolean validation)
        throws XmlMappingException, IOException {
    Assert.notNull(source, "StreamSource is null");
    Assert.notNull(extraTransportClass, "ExtraTransportClass is null");

    final Unmarshaller unmarshaller = findUnmarschaller(validation);
    final Object responseObject = unmarshaller.unmarshal(source);
    logger.debug("ResponseObject Class: {}", responseObject.getClass());
    Assert.notNull(responseObject, "Response is null");
    X extraTransport = null;//from w ww.  ja  v a2  s .c om
    if (ResponseTransport.class.isAssignableFrom(responseObject.getClass())) {
        extraTransport = extraTransportClass.cast(responseObject);
    } else if (JAXBElement.class.isAssignableFrom(responseObject.getClass())) {
        // TODO Wie funktioniert es besser?
        @SuppressWarnings("rawtypes")
        final JAXBElement jaxbElementResponse = JAXBElement.class.cast(responseObject);
        final Object jaxBElementValue = jaxbElementResponse.getValue();

        Assert.isAssignable(extraTransportClass, jaxBElementValue.getClass(),
                "JaxBElement.value  can not be converted to the response.ResponseTransport");
        extraTransport = extraTransportClass.cast(jaxBElementValue);
    } else {
        throw new IllegalArgumentException(
                "Response can not be converted to the response.ResponseTransport. ResponseObjectClass: "
                        + responseObject.getClass());
    }
    return extraTransport;
}

From source file:net.refractions.udig.catalog.IService.java

/**
 * Will attempt to morph into the adaptee, and return that object. Harded coded to capture the
 * IService contract.//from   www.  j av a  2  s. co  m
 * <p>
 * That is we *must* resolve the following:
 * <ul>
 * <li>IService: this
 * <li>IServiceInfo.class: getInfo
 * <li>ICatalog.class: parent
 * </ul>
 * Recomended adaptations:
 * <ul>
 * <li>ImageDescriptor.class: for a custom icon 
 * <li>List.class: members
 * </ul>
 * May Block.
 * <p>
 * Example implementation:<pre><code>
 * public &lt;T&gt; T resolve( Class&lt;T&gt; adaptee, IProgressMonitor monitor ) throws IOException {
 *     if (monitor == null) monitor = new NullProgressMonitor(); 
 *     if (adaptee == null)
 *         throw new NullPointerException("No adaptor specified" );
 *         
 *     if (adaptee.isAssignableFrom(API.class)) {
 *         return adaptee.cast(getAPI(monitor));
 *     }
 *     return super.resolve(adaptee, monitor);
 * }
 * </code></pre>
 * @param adaptee
 * @param monitor
 * @return instance of adaptee, or null if unavailable (IServiceInfo and List<IGeoResource>
 *         must be supported)
 * @see IServiceInfo
 * @see IGeoResource
 * @see IResolve#resolve(Class, IProgressMonitor)
 */
public <T> T resolve(Class<T> adaptee, IProgressMonitor monitor) throws IOException {
    if (monitor == null)
        monitor = new NullProgressMonitor();

    if (adaptee == null) {
        throw new NullPointerException("No adaptor specified"); //$NON-NLS-1$
    }
    if (adaptee.isAssignableFrom(IServiceInfo.class)) {
        return adaptee.cast(createInfo(monitor));
    }
    if (adaptee.isAssignableFrom(IService.class)) {
        monitor.done();
        return adaptee.cast(this);
    }
    if (adaptee.isAssignableFrom(ICatalog.class)) {
        return adaptee.cast(parent(monitor));
    }
    IResolveManager rm = CatalogPlugin.getDefault().getResolveManager();
    if (rm.canResolve(this, adaptee)) {
        return rm.resolve(this, adaptee, monitor);
    }
    return null; // no adapter found (check to see if ResolveAdapter is registered?)
}