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:net.bican.wordpress.Main.java

private static void printList(List<?> r, Class<?> cl, boolean oneLiner) {
    boolean headerPrinted = false;
    for (Object o : r) {
        cl.cast(o);
        if (!headerPrinted) {
            if ((!(o instanceof String)) && (oneLiner)) {
                System.out.println(((StringHeader) o).getStringHeader());
            }/*from w  w  w .  java  2  s.c  om*/
            headerPrinted = true;
        }
        if (oneLiner) {
            System.out.println(((XmlRpcMapped) o).toOneLinerString());
        } else {
            System.out.println(o);
        }
    }
}

From source file:com.brienwheeler.svc.monitor.telemetry.impl.TelemetryServiceBaseTestUtils.java

@SuppressWarnings("unchecked")
public static <T> T findProcessor(TelemetryServiceBase telemetryServiceBase, Class<T> clazz) {
    List<ITelemetryInfoProcessor> processors = (List<ITelemetryInfoProcessor>) ReflectionTestUtils
            .getField(telemetryServiceBase, "processors");
    if (processors != null) {
        for (ITelemetryInfoProcessor proc : processors)
            if (clazz.isAssignableFrom(proc.getClass()))
                return clazz.cast(proc);
    }//from  ww  w .ja  v a2 s  .c om

    throw new IllegalStateException("no " + clazz.getSimpleName() + " found in test context!");
}

From source file:org.apache.nifi.minifi.c2.security.authorization.GrantedAuthorityAuthorizer.java

private static <T, E extends Throwable> T as(Class<T> clazz, Object object,
        Function<Object, E> exceptionSupplier) throws E {
    if (object == null) {
        return null;
    }/*from   w  ww  .  j  av a  2  s  .c om*/
    if (!clazz.isInstance(object)) {
        throw exceptionSupplier.apply(object);
    }
    return clazz.cast(object);
}

From source file:Utils.java

/**
 * Create a typesafe copy of a raw list.
 * @param rawList an unchecked list/*from  w  w w  . j a v  a 2  s.co  m*/
 * @param type the desired supertype of the entries
 * @param strict true to throw a <code>ClassCastException</code> if the raw list has an invalid entry,
 *               false to skip over such entries (warnings may be logged)
 * @return a typed list guaranteed to contain only entries assignable
 *         to the named type (or they may be null)
 * @throws ClassCastException if some entry in the raw list was not well-typed, and only if <code>strict</code> was true
 */
public static <E> List<E> checkedListByCopy(List rawList, Class<E> type, boolean strict)
        throws ClassCastException {
    List<E> l = (rawList instanceof RandomAccess) ? new ArrayList<E>(rawList.size()) : new LinkedList<E>();
    Iterator it = rawList.iterator();
    while (it.hasNext()) {
        Object e = it.next();
        try {
            l.add(type.cast(e));
        } catch (ClassCastException x) {
            if (strict) {
                throw x;
            } else {
                System.out.println("not assignable ");
            }
        }
    }
    return l;
}

From source file:Utils.java

/**
 * Create a typesafe copy of a raw map./* w  w w. ja va 2s.  c om*/
 * @param rawMap an unchecked map
 * @param keyType the desired supertype of the keys
 * @param valueType the desired supertype of the values
 * @param strict true to throw a <code>ClassCastException</code> if the raw map has an invalid key or value,
 *               false to skip over such map entries (warnings may be logged)
 * @return a typed map guaranteed to contain only keys and values assignable
 *         to the named types (or they may be null)
 * @throws ClassCastException if some key or value in the raw map was not well-typed, and only if <code>strict</code> was true
 */
public static <K, V> Map<K, V> checkedMapByCopy(Map rawMap, Class<K> keyType, Class<V> valueType,
        boolean strict) throws ClassCastException {
    Map<K, V> m2 = new HashMap<K, V>(rawMap.size() * 4 / 3 + 1);
    Iterator it = rawMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry e = (Map.Entry) it.next();
        try {
            m2.put(keyType.cast(e.getKey()), valueType.cast(e.getValue()));
        } catch (ClassCastException x) {
            if (strict) {
                throw x;
            } else {
                System.out.println("not assignable");
            }
        }
    }
    return m2;
}

From source file:Main.java

public static <T> T parse(final Class<T> clazz, final InputStream inputStream) {
    try {/*from w w w . ja  v a2  s.  c om*/
        final JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        final Object deserialized = jaxbUnmarshaller.unmarshal(inputStream);
        if (clazz.isAssignableFrom(deserialized.getClass())) {
            return clazz.cast(deserialized);
        } else {
            final JAXBElement<T> jaxbElement = (JAXBElement<T>) deserialized;
            return jaxbElement.getValue();
        }
    } catch (final JAXBException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.adobe.acs.commons.util.TypeUtil.java

/**
 * Converts a limited set of String representations to their corresponding Objects
 * <p/>/* w  ww  . j a v a2s. c  om*/
 * Supports
 * * Double
 * * Long
 * * Integer
 * * Boolean (true/false)
 * * Dates in string format of ISODateTimeFormat
 * <p/>
 * Else, null is returned.
 *
 * @param data  the String representation of the data
 * @param klass the target class type of the provided data
 * @param <T>   the target class type of the provided data
 * @return the derived object representing the data as specified by the klass
 */
public static <T> T toObjectType(String data, Class<T> klass) {
    if (Double.class.equals(klass)) {
        try {
            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 (Integer.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:org.apache.tuscany.sca.binding.rest.provider.RESTBindingInvoker.java

private static <T extends Annotation> T getAnnotation(Annotation[] annotations, Class<T> type) {
    for (Annotation a : annotations) {
        if (a.annotationType() == type) {
            return type.cast(a);
        }//from   ww  w  .j a v a2  s .c  o  m
    }
    return null;
}

From source file:com.joyent.manta.client.multipart.AbstractMultipartManager.java

/**
 * <p>Uses reflection to read a private field from a {@link MantaClient}
 * instance.</p>/*from  www. ja v  a2  s  .c  om*/
 *
 * <p>We use reflection to read private fields from {@link MantaClient} as
 * part of a compromise between package level separation and private/default
 * scoping. Essentially, it makes sense to put multipart related classes
 * in their own package because the package in which {@link MantaClient} is
 * contained is already crowded. However, by making that decision there is
 * no scoping mechanism available in Java to allow us to share
 * methods/fields between packages without giving other packages access.
 * Thus, we scope the methods/fields that shouldn't be available to a user
 * of the SDK as private/protected/default and use reflection
 * <em>sparingly</em> to access the values from another package. Particular
 * care has been paid to making this reflection-based reads outside of
 * performance sensitive code paths.</p>
 *
 * @param fieldName field name to read
 * @param mantaClient Manta client instance to read fields from
 * @param returnType type of field
 * @param <T> field type
 * @return value of the field
 */
protected static <T> T readFieldFromMantaClient(final String fieldName, final MantaClient mantaClient,
        final Class<T> returnType) {
    final Field field = FieldUtils.getField(MantaClient.class, fieldName, true);

    try {
        Object object = FieldUtils.readField(field, mantaClient, true);
        return returnType.cast(object);
    } catch (IllegalAccessException e) {
        throw new MantaMultipartException("Unable to access httpHelper " + "field on MantaClient");
    }
}

From source file:Main.java

/**
 * Return the first ancestor of <code>component</code> (beginning with itself) that is an
 * {@link Class#isInstance(Object) instance of} <code>c</code>. If <code>component</code> is in
 * a popup, {@link JPopupMenu#getInvoker()} is used instead of {@link Component#getParent()}.
 * //from   w w  w.  j  av a  2s  .com
 * @param <C> type of class.
 * @param c the searched for class.
 * @param component the component.
 * @return the first ancestor or <code>null</code> if none match.
 */
public static final <C> C getAncestorOrSelf(final Class<C> c, Component component) {
    while (component != null && !c.isInstance(component)) {
        if (component instanceof JPopupMenu) {
            // popups are in a JLayeredPane in the root pane
            component = ((JPopupMenu) component).getInvoker();
        } else {
            component = component.getParent();
        }
    }
    return c.cast(component);
}