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.healthmarketscience.rmiio.RemoteWrapper.java

/**
 * Simple wrapper generator which creates a Proxy for the given remote
 * interface. This proxy will make all the remote calls through the {@link #invoke} method which makes the actual method calls on the
 * underlying stub within the retry logic.
 * //from  w w  w  .j a va 2s. c om
 * @param iface
 *           the remote interface to be implemented
 * @param stub
 *           the underlying implementation of the remote interface which
 *           will actually make the remote calls
 * @param retry
 *           the retry policy to use for the remote calls
 * @param log
 *           the log to use during retry handling
 * @return a proxy for the given interface using the given retry strategy
 */
public static <R> R wrap(Class<R> iface, R stub, RemoteRetry retry, Log log) {
    RemoteWrapper<R> wrapper = new RemoteWrapper<R>(stub, retry, log);
    return iface.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class<?>[] { iface }, wrapper));
}

From source file:Main.java

public static <T> List<T> ofType(List<Object> list, Class<T> targetClass) {
    List<T> result = new ArrayList<T>();

    for (Object object : list) {
        boolean isTargetClass = object.getClass().equals(targetClass);
        if (isTargetClass) {
            result.add(targetClass.cast(object));
        }/*  ww  w .  java 2 s.  com*/
    }

    return result;
}

From source file:Main.java

public static <T> List<T> filterByType(Iterable<?> collection, Class<T> expectedType) {
    List<T> filtered = new LinkedList<T>();
    if (collection != null) {
        for (Object item : collection) {
            if (item != null && expectedType.isInstance(item)) {
                filtered.add(expectedType.cast(item));
            }//from w w  w  . j ava 2 s .  c o m
        }
    }
    return filtered;
}

From source file:Main.java

public static <T> T[] toTypedArray(Collection<?> collection, Class<T> type) {
    @SuppressWarnings("unchecked")
    T[] array = (T[]) Array.newInstance(type, collection.size());
    Object[] data = collection.toArray();
    for (int i = 0; i < array.length; i++) {
        array[i] = type.cast(data[i]);
    }/*from   ww w  .  ja  v a2s. c om*/
    return array;

}

From source file:io.sqp.core.util.TypeUtil.java

/**
 * Checks a value to be not null and tries to map it to a given class.
 * The method first checks the value to be not-null and then if it's assignable to the desired class.
 * If it's not directly assignable (e.g. a int is not assignable to a Double), Jackson's object mapper
 * is used to convert the value, as it is able to map any classes if they are somehow compatible.
 * Therefore this method can also be used to map a {@literal List<Integer>} to an {@literal int[]}.
 * This method also does range checks, e.g. it fails if you try to convert 2^30 to a Short.
 * @param value The value to be checked and mapped.
 * @param clazz The class the value should be mapped to
 * @param what A brief description of the message that is used in a potential error message. E.g. "the identifier"
 * @param <T> The desired object type
 * @return The converted, non-null object.
 * @throws IllegalArgumentException If the value is null or cannot be converted to the desired type
 *//*  ww w  . j  a v  a  2s.c om*/
public static <T> T checkAndConvert(Object value, Class<T> clazz, String what) {
    if (value == null) {
        throw new IllegalArgumentException(what + " is null.");
    }
    if (clazz.isAssignableFrom(value.getClass())) {
        return clazz.cast(value);
    }
    try {
        return _objectMapper.convertValue(value, clazz);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                what + " could not be mapped to type " + clazz.getName() + ": " + e.getMessage(), e);
    }
}

From source file:de.zib.gndms.GORFX.service.TaskFlowServiceAux.java

public static <T extends Order> DelegatingOrder<T> setOrderAsDelegate(Order order, TaskFlow<T> taskFlow,
        TaskFlowFactory<T, ?> factory) {
    Class<T> orderClass = factory.getOrderClass();
    if (taskFlow.getOrder() == null) {
        DelegatingOrder<T> delegate = factory.getOrderDelegate(orderClass.cast(order));
        taskFlow.setOrder(delegate);/*from w ww  .  ja v  a2s  .com*/
    } else
        taskFlow.getOrder().setOrderBean(orderClass.cast(order));

    return taskFlow.getOrder();
}

From source file:Main.java

/**
 * Filters Views based on the given class type.
 * /*www .  ja  va2s  . c o  m*/
 * @param classToFilterBy the class to filter
 * @param viewList the Iterable to filter from
 * @return an ArrayList with filtered views
 */

public static <T> ArrayList<T> filterViews(Class<T> classToFilterBy, Iterable<?> viewList) {
    ArrayList<T> filteredViews = new ArrayList<T>();
    for (Object view : viewList) {
        if (view != null && classToFilterBy.isAssignableFrom(view.getClass())) {
            filteredViews.add(classToFilterBy.cast(view));
        }
    }
    viewList = null;
    return filteredViews;
}

From source file:com.jroossien.boxx.util.Utils.java

public static <T> T convertInstance(Object o, Class<T> clazz) {
    try {/*  w w w .j  a  v a2  s . c o  m*/
        return clazz.cast(o);
    } catch (ClassCastException e) {
        return null;
    }
}

From source file:com.activecq.api.utils.TypeUtil.java

public static <T> T toObjectType(String data, Class<T> klass) {
    if (Double.class.equals(klass)) {
        try {/*  ww w . ja v a  2s  .com*/
            return klass.cast(Double.parseDouble(data));
        } catch (NumberFormatException ex) {
            return null;
        }
    } else if (Long.class.equals(klass)) {
        try {
            return klass.cast(Long.parseLong(data));
        } catch (NumberFormatException ex) {
            return null;
        }
    } else if (StringUtils.equalsIgnoreCase("true", data)) {
        return klass.cast(Boolean.TRUE);
    } else if (StringUtils.equalsIgnoreCase("false", data)) {
        return klass.cast(Boolean.FALSE);
    } else if (JSON_DATE.matcher(data).matches()) {
        return klass.cast(ISODateTimeFormat.dateTimeParser().parseDateTime(data).toDate());
    } else {
        return klass.cast(data);
    }
}

From source file:io.syndesis.runtime.Recordings.java

static public <T> T recorder(Object object, Class<T> as) {
    if (as.isInterface()) {
        // If it's just an interface, use standard java reflect proxying
        return as.cast(Proxy.newProxyInstance(as.getClassLoader(), new Class[] { as },
                new RecordingInvocationHandler(object)));
    }//from   w ww  .j  av a2s . c  om

    // If it's a class then use gclib to implement a subclass to implement proxying
    RecordingInvocationHandler ih = new RecordingInvocationHandler(object);
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(as);
    enhancer.setInterfaces(new Class[] { RecordingProxy.class });
    enhancer.setCallback(new org.springframework.cglib.proxy.InvocationHandler() {
        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            return ih.invoke(o, method, objects);
        }
    });
    return as.cast(enhancer.create());
}