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.cedarsoft.configuration.xml.ConfigurationAccessTest.java

License:asdf

@Test
public void testCallback() {
    DefaultValueProvider defaultValueProvider = new DefaultValueProvider() {
        @Override/*from  w  w  w.  ja  v  a  2s  .com*/
        @Nonnull
        public <T> T getDefaultValue(@Nonnull String key, @Nonnull Class<T> type) {
            return type.cast("1234");
        }
    };
    ConfigurationAccess<String> configurationAccess = new ConfigurationAccess<String>(configuration,
            String.class, "key", defaultValueProvider);
    assertEquals("1234", configurationAccess.resolve());

    assertEquals("1234", configuration.getString("key"));
}

From source file:com.consol.citrus.admin.converter.endpoint.AbstractEndpointConverter.java

/**
 *
 * @param setter//from w w  w  .  j ava 2s  . c  o  m
 * @param value
 * @return
 */
private Object getMethodArgument(Method setter, String value) {
    Class<?> type = setter.getParameterTypes()[0];
    if (type.isInstance(value)) {
        return type.cast(value);
    }

    try {
        return new SimpleTypeConverter().convertIfNecessary(value, type);
    } catch (ConversionNotSupportedException e) {
        if (String.class.equals(type)) {
            return value.toString();
        }

        throw new ApplicationRuntimeException("Unable to convert method argument type", e);
    }
}

From source file:de.pixida.logtest.designer.automaton.BaseEdge.java

<T> T getSourceNode(final Class<T> clz) {
    Validate.notNull(clz);//from  w ww. java 2  s.  c  o  m
    Validate.isTrue(this.sourceNodeIsOfType(clz));
    return clz.cast(this.sourceNode);
}

From source file:de.pixida.logtest.designer.automaton.BaseEdge.java

<T> T getTargetNode(final Class<T> clz) {
    Validate.notNull(clz);/*from   ww  w.ja  va2  s. c  o  m*/
    Validate.isTrue(this.targetNodeIsOfType(clz));
    return clz.cast(this.targetNode);
}

From source file:com.orchestra.portale.controller.GetPageController.java

@RequestMapping(value = "/getPage", params = "id")
public ModelAndView getPagebyId(@RequestParam(value = "id") String id) {
    ModelAndView model = new ModelAndView("page");
    Pages page = pm.findPageById(id);//from   www .  j av a 2 s  .co  m
    model.addObject("pages", page);
    ArrayList<CompletePOI> pois = new ArrayList<CompletePOI>();

    if (page.getIdPoiList() != null) {
        pois = (ArrayList<CompletePOI>) pm.getCompletePoisById(page.getIdPoiList());
        model.addObject("poivicini", pois);
    } else {
        if (page.getCategorySlugList() != null) {

            Iterable<CompletePOI> poilist = pm.getCompletePoiByCategories(page.getCategorySlugList());
            model.addObject("poivicini", poilist);
        }
    }

    if (page.getComponents() != null) {
        for (AbstractPoiComponent comp : page.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();
            Class c;
            try {
                c = Class.forName(slug);
                model.addObject(cname, c.cast(comp));
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(GetPageController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
    return model;
}

From source file:cz.cvut.wpa.prjmgr.DAO.HibernateDAO.java

public <ENTITY> ENTITY getByPropertyUnique(String property, Object value, Class<ENTITY> clazz) {
    ENTITY e;/*from w ww  .java  2s  . c  o  m*/
    if (value == null) {
        e = clazz.cast(getEntityManager()
                .createQuery("FROM " + clazz.getSimpleName() + " WHERE " + property + " IS NULL")
                .getSingleResult());
    } else {
        e = clazz.cast(getEntityManager()
                .createQuery("FROM " + clazz.getSimpleName() + " WHERE " + property + " = :value")
                .setParameter("value", value).getSingleResult());
    }
    return e;
}

From source file:org.killbill.billing.client.KillBillHttpClient.java

private static <T> T createEmptyResult(final Class<T> clazz) {// Return empty list for KillBillObjects instead of null for convenience
    if (Iterable.class.isAssignableFrom(clazz)) {
        for (final Constructor constructor : clazz.getConstructors()) {
            if (constructor.getParameterTypes().length == 0) {
                try {
                    return clazz.cast(constructor.newInstance());
                } catch (final InstantiationException e) {
                    return null;
                } catch (final IllegalAccessException e) {
                    return null;
                } catch (final InvocationTargetException e) {
                    return null;
                }//w  w w. j av a 2 s  .c  o  m
            }
        }
        return null;
    } else {
        return null;
    }
}

From source file:Main.java

/** Evaluates an XPath returning null if not found. <br>
 *  <br>//from w  w w . j av a 2s  .c o  m
 *  This is intended for use with pre-defined XPaths stored as constants,
 *  where runtime exceptions should not be possible.
 *  @param expression The XPath expression to evaluate.
 *  @param item       The {@link Node} or other item to evaluate the XPath on.
 *  @param type       The type to return, this must be one of the following:
 *                    {@link String}, {@link CharSequence}, {@link Boolean},
 *                    {@link Node}, {@link NodeList}, {@link Double}, or
 *                    {@link Number}.
 *  @throws AssertionError If the nested call to <tt>XPath.newInstance(path)</tt>
 *                         throws an {@link XPathExpressionException}.
 */
public static <T> T evalXPath(String expression, Object item, Class<T> type) {
    Object val;

    if (type == String.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == CharSequence.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == Boolean.class)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Boolean.TYPE)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Node.class)
        val = evalXPath(expression, item, XPathConstants.NODE);
    else if (type == NodeList.class)
        val = evalXPath(expression, item, XPathConstants.NODESET);
    else if (type == Double.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Double.TYPE)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Number.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else
        throw new IllegalArgumentException("Invalid type given " + type);

    return type.cast(val);
}

From source file:com.orchestra.portale.controller.GetPageController.java

@RequestMapping(value = "/page", params = "sec")
public ModelAndView getPagebySlug(@RequestParam(value = "sec") String sluginp) {
    ModelAndView model = new ModelAndView("page");
    if (sluginp.equals("home")) {
        model = new ModelAndView("home");
    }//from  w  w  w. ja v a  2  s .  com
    Pages page = pm.findPageBySlug(sluginp);
    model.addObject("pages", page);
    ArrayList<CompletePOI> pois = new ArrayList<CompletePOI>();

    if (page.getIdPoiList() != null) {
        pois = (ArrayList<CompletePOI>) pm.getCompletePoisById(page.getIdPoiList());
        model.addObject("poivicini", pois);
    } else {
        if (page.getCategorySlugList() != null) {

            Iterable<CompletePOI> poilist = pm.getCompletePoiByCategories(page.getCategorySlugList());
            model.addObject("poivicini", poilist);
        }
    }
    if (page.getComponents() != null) {
        for (AbstractPoiComponent comp : page.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();
            Class c;
            try {
                c = Class.forName(slug);
                model.addObject(cname, c.cast(comp));
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(GetPageController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
    return model;
}

From source file:hudson.model.Actionable.java

/**
 * Gets the action (first instance to be found) of a specified type that contributed to this build.
 *
 * @param type// w  w w.  j av a2  s.  c  o m
 * @return The action or <code>null</code> if no such actions exist.
 * @see #getActions(Class)
 */
public <T extends Action> T getAction(Class<T> type) {
    for (Action a : getActions())
        if (type.isInstance(a))
            return type.cast(a);
    return null;
}