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.orchestra.portale.controller.EditDeepeningPageController.java

@RequestMapping(value = "/editdpage", params = "name")
public ModelAndView editPoi(@RequestParam(value = "name") String name) {
    ModelAndView model = new ModelAndView("editdpageform");
    try {//from  ww  w.  j  av  a 2s  .  co  m
        DeepeningPage poi = pm.findDeepeningPageByName(name);
        model.addObject("nome", poi.getName());
        model.addObject("cat", poi.getCategories());
        model.addObject("id", poi.getId());

        for (AbstractPoiComponent comp : poi.getComponents()) {

            //associazione delle componenti al model tramite lo slug
            String slug = comp.slug();
            int index = slug.lastIndexOf(".");
            String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();

            try {
                Class c = Class.forName(slug);
                model.addObject(cname, c.cast(comp));
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(PoiViewController.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

        return model;
    } catch (RuntimeException e) {
        ModelAndView model2 = new ModelAndView("errorViewPoi");
        model2.addObject("err", "Errore impossibile trovare la paginda d'approfondimento: " + e.toString());
        return model2;
    }
}

From source file:com.quartercode.disconnected.sim.run.Ticker.java

/**
 * Returns the tick actions which has the given type as a superclass.
 * /*from  w  ww.j  a  v a 2 s .c o  m*/
 * @param type The type to use.
 * @return The tick actions which has the given type as a superclass.
 */
public <T> T getAction(Class<T> type) {

    for (TickAction action : actions) {
        if (type.isAssignableFrom(action.getClass())) {
            return type.cast(action);
        }
    }

    return null;
}

From source file:com.adobe.acs.tools.csv.impl.Column.java

private <T> T toObjectType(String data, Class<T> klass) {
    data = StringUtils.trim(data);/*w  w w . j av  a 2s.c om*/

    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 ((Date.class.equals(Date.class) || Calendar.class.equals(Calendar.class))
            && ISO_DATE_PATTERN.matcher(data).matches()) {
        return klass.cast(ISODateTimeFormat.dateTimeParser().parseDateTime(data).toCalendar(Locale.US));
    } else {
        return klass.cast(data);
    }
}

From source file:net.logstash.logback.ConfigurationTest.java

private <T extends JsonProvider<ILoggingEvent>> T getInstance(List<JsonProvider<ILoggingEvent>> providers,
        Class<T> clazz) {
    for (JsonProvider<ILoggingEvent> jsonProvider : providers) {
        if (clazz.isInstance(jsonProvider)) {
            return clazz.cast(jsonProvider);
        }/* www . java  2s . c  om*/
    }
    return null;
}

From source file:org.ops4j.pax.url.mvn.internal.wagon.ConfigurableHttpWagon.java

private <T> T getField(Class<T> clazz, String name) {
    try {/*from w  w w.  j a v  a2  s  .co  m*/
        Field field = AbstractHttpClientWagon.class.getDeclaredField(name);
        field.setAccessible(true);
        return clazz.cast(field.get(this));
    } catch (NoSuchFieldException e) {
        throw new IllegalStateException("Unable to retrieve field " + name, e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Unable to retrieve field " + name, e);
    }
}

From source file:be.fedict.eid.pkira.xkmsws.util.XMLMarshallingUtil.java

/**
 * Extracts the first element from the list matching the type.
 * //w w w .j a va  2  s .  c  o  m
 * @param <T>
 *            expected type.
 * @param clazz
 *            expected type.
 * @param list
 *            list with either this type of a JAXBElement with this type.
 * @return the first matching element.
 */
public <T> T getFromList(Class<T> clazz, List<Object> list) {
    for (Object object : list) {
        if (clazz.isInstance(object)) {
            return clazz.cast(object);
        }
        if (object instanceof JAXBElement<?>) {
            JAXBElement<?> jaxbElement = (JAXBElement<?>) object;
            if (jaxbElement.getDeclaredType().equals(clazz)) {
                return clazz.cast(jaxbElement.getValue());
            }
        }
    }

    return null;
}

From source file:com.formkiq.core.form.bean.StringConverter.java

/**
 * Convert the specified input object into an output object of the
 * specified type.// ww w.j a  va  2s.c o m
 *
 * @param <T> Target type of the conversion.
 * @param type Data type to which this value should be converted.
 * @param value The input value to be converted.
 * @return The converted value.
 * @throws Throwable if an error occurs converting to the specified type
 * @since 1.8.0
 */
@SuppressWarnings("unchecked")
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {
    // We have to support Object, too, because this class is sometimes
    // used for a standard to Object conversion
    if (String.class.equals(type) || Object.class.equals(type)) {
        return type.cast(value.toString());
    }

    if (type.isAssignableFrom(List.class)) {
        return (T) new ArrayList<>(Arrays.asList(value.toString().split("\n")));
    }

    throw conversionException(type, value);
}

From source file:com.quartercode.eventbridge.def.bridge.DefaultBridge.java

@Override
public <T extends BridgeModule> T getModule(Class<T> type) {

    Validate.notNull(type, "Module type for module retrieval cannot be null");

    for (BridgeModule module : modules) {
        if (type.isInstance(module)) {
            return type.cast(module);
        }/*from   www  .  j  a v  a 2  s.co m*/
    }

    return null;
}

From source file:eu.udig.catalog.jgrass.core.JGTtmsService.java

/**
 * resolve the adaptee to the location folder file
 *///  www. ja va2s. c o m
public <T> T resolve(Class<T> adaptee, IProgressMonitor monitor) throws IOException {
    if (adaptee == null)
        return null;

    if (adaptee.isAssignableFrom(IServiceInfo.class)) {
        return adaptee.cast(getInfo(monitor));
    }
    if (adaptee.isAssignableFrom(File.class)) {
        return adaptee.cast(tmsPropertiesFile);
    }
    // bad call to resolve
    return super.resolve(adaptee, monitor);
}

From source file:org.vas.test.rest.RestImpl.java

protected <T> T lookupBody(Class<T> klass, byte[] content) throws Exception {
    if (klass == String.class) {
        return content == null ? klass.cast("") : klass.cast(new String(content));
    } else if (klass == byte[].class) {
        return klass.cast(content);
    } else if (klass == Void.class) {
        return null;
    } else {/*from   w ww .jav  a2s.com*/
        try {
            return GsonUtils.GSON.fromJson(new String(content), klass);
        } catch (JsonSyntaxException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Fail to parse json", e);
            }
            return null;
        }
    }
}