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:ch.sdi.core.impl.data.filter.CollectFilter.java

/**
 * Typesafe extraction of the configured field (property FieldName)
 * <p>//  w  w  w  .j av a 2s.co  m
 * @param aDataset
 *        dataset to be examined
 * @param aClass
 *        desired class of the field value
 * @return
 */
protected T getFieldValue(Dataset aDataset, Class<T> aClass) {
    Object value = aDataset.get(myFieldName);

    if (value == null) {
        myLog.debug("dataset does not contain a field named " + myFieldName);
        return null;
    }

    if (!(aClass.isInstance(value))) {
        myLog.warn("value of field " + myFieldName + " is not instance of " + aClass.getSimpleName() + ", but: "
                + value.getClass().getName());
        return null;
    }

    return aClass.cast(value);
}

From source file:ch.sdi.report.SdiReporter.java

/**
 * @param aCollector//from ww  w  .  j  a v  a 2s  . c o  m
 * @param aString
 * @return
 */
private <T> T findSimpleEntry(ReportType aReportType, String aKey, Class<T> aClass) {
    Collection<ReportMsg> messages = findOfTypes(aReportType);
    for (ReportMsg msg : messages) {
        if (msg.getKey().equals(aKey)) {
            Object o = msg.getValue();

            if (aClass.isInstance(o)) {
                return aClass.cast(o);

            } // if aClass.isInstance( obj )

            myLog.warn("Entry found for report type " + aReportType + " and key " + aKey
                    + ", but not of desired type! Entry: " + o.getClass().getName() + "; expected: "
                    + aClass.getName());
            return null;

        } // if key.equals( aKey )
    }

    myLog.warn("No entry found for report type " + aReportType + " and key " + aKey);
    return null;
}

From source file:org.solmix.runtime.support.spring.SpringBeanProvider.java

private <T> Collection<? extends T> _doGetBeansOfType(ApplicationContext context, Class<T> type) {
    if (context != null) {
        Set<String> s = new LinkedHashSet<String>(
                Arrays.asList(context.getBeanNamesForType(type, false, false)));
        s.removeAll(passThroughs);//from ww w  .j a  v  a  2s .c  o m
        List<T> lst = new LinkedList<T>();
        for (String n : s) {
            lst.add(type.cast(context.getBean(n, type)));
        }
        if (context.getParent() != null) {
            lst.addAll(_doGetBeansOfType(context.getParent(), type));
        }
        return lst;
    }
    return null;

}

From source file:hudson.tasks.test.TestObject.java

/**
 * Gets a test action of the class passed in. 
 * @param klazz//from www . ja v a2 s  .c  om
 * @param <T> an instance of the class passed in
 */
@Override
public <T> T getTestAction(Class<T> klazz) {
    for (TestAction action : getTestActions()) {
        if (klazz.isAssignableFrom(action.getClass())) {
            return klazz.cast(action);
        }
    }
    return null;
}

From source file:edu.purdue.cybercenter.dm.service.CqlService.java

private Object getPropertyValue(Object object, String propertyName)
        throws IllegalArgumentException, IllegalAccessException {
    Object value = null;// w w  w .  j a  v a 2  s.c  o  m

    Class<?> objectClass = object.getClass();
    do {
        try {
            Field field = objectClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            value = field.get(objectClass.cast(object));
            break;
        } catch (NoSuchFieldException ex) {
        }
    } while ((objectClass = objectClass.getSuperclass()) != null);

    return value;
}

From source file:de.Keyle.MyPet.api.util.hooks.PluginHookManager.java

/**
 * searches for an instance of a plugin/*  w w w .ja v a2 s  .co  m*/
 *
 * @param clazz class of the plugin
 * @return instance of the plugin
 */
public <T extends JavaPlugin> Optional<T> getPluginInstance(Class<T> clazz) {
    try {
        T plugin = JavaPlugin.getPlugin(clazz);
        if (plugin != null) {
            return Optional.of(plugin);
        }
    } catch (NoSuchMethodError e) {
        for (Plugin p : Bukkit.getPluginManager().getPlugins()) {
            if (clazz.isInstance(p)) {
                T plugin = clazz.cast(p);
                return Optional.of(plugin);
            }
        }
    }
    return Optional.absent();
}

From source file:com.github.yongchristophertang.engine.java.handler.JsonTransformer.java

/**
 * Transform the json result to an instance of T.
 *
 * @param clazz the type class of transformed object
 *///www .j  a  va  2  s  . com
public <T> T object(String expression, Class<T> clazz) {
    Objects.nonNull(expression);
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    try {
        return expression == null ? mapper.readValue(context, clazz)
                : mapper.readValue(JsonPath.compile(expression).read(context).toString(), clazz);
    } catch (Exception e) {
        return clazz.cast(JsonPath.compile(expression).read(context));
    }
}

From source file:com.l2jserver.util.transformer.impl.ArrayTransformer.java

@Override
@SuppressWarnings("unchecked")
public T[] untransform(Class<? extends T[]> type, String stringValue) {
    final Transformer<T> transformer = (Transformer<T>) TransformerFactory
            .getTransfromer(type.getComponentType());
    final String[] stringValues = StringUtils.split(stringValue, '|');
    final Object values = Array.newInstance(type.getComponentType(), stringValues.length);
    int i = 0;/* w w w  .j  a v a2  s. c  o m*/
    for (final String value : stringValues) {
        Array.set(values, i++, transformer.untransform((Class<T>) type.getComponentType(), value));
    }

    return type.cast(values);
}

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

@Override
public <T> T convert(Class<T> type, Object value) {
    ListInfo info = null;/*from w w  w .  jav  a 2s  .c om*/

    if (value instanceof JSONObject) {
        JSONObject json = (JSONObject) value;
        info = new ListInfo();

        info.setAccessLevel(json.getString("access_level"));
        info.setAddress(json.getString("address"));
        info.setCount(json.getInt("members_count"));
        info.setCreated(json.getString("created_at"));
        info.setDescription(json.getString("description"));
        info.setName(json.getString("name"));

    }

    return type.cast(info);
}

From source file:de.tuberlin.uebb.jbop.optimizer.utils.NodeHelper.java

private static <T> T getConstantValue(final AbstractInsnNode node, final Class<T> clazz)
        throws NotANumberException {
    if (node == null) {
        throw new NotANumberException();
    }//w  w  w  . j  a v  a  2  s . c  o m
    if (node.getOpcode() == ACONST_NULL) {
        return null;
    }
    if (!(node instanceof LdcInsnNode)) {
        throw new NotANumberException();
    }
    try {
        final Object value = ((LdcInsnNode) node).cst;
        return clazz.cast(value);
    } catch (final ClassCastException cce) {
        throw new NotANumberException();
    }
}