List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:de.cosmocode.collections.utility.Convert.java
private static <E extends Enum<E>> E doIntoEnum(Object value, Class<E> enumType) { Preconditions.checkNotNull(enumType, "EnumType"); if (enumType.isInstance(value)) return enumType.cast(value); final Long ordinal = doIntoLong(value); if (ordinal == null) { final String name = doIntoString(value); if (name == null) return null; try {/*from w w w .j ava 2 s.c o m*/ return Enum.valueOf(enumType, name.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } else { try { return Enums.valueOf(enumType, ordinal.intValue()); } catch (IndexOutOfBoundsException e) { return null; } } }
From source file:com.qwazr.server.GenericServer.java
/** * Returns the named attribute. The method checks the type of the object. * * @param context the context to request * @param name the name of the attribute * @param type the expected type/* w w w. jav a2 s. co m*/ * @param <T> the expected object * @return the expected object */ public static <T> T getContextAttribute(final ServletContext context, final String name, final Class<T> type) { final Object object = context.getAttribute(name); if (object == null) return null; if (!object.getClass().isAssignableFrom(type)) throw new RuntimeException( "Wrong returned type: " + object.getClass().getName() + " - Expected: " + type.getName()); return type.cast(object); }
From source file:com.startechup.tools.ModelParser.java
/** * Parses a json object into a {@link Map} object having the json property name as key and json property * value as the map value.//from w w w .j av a 2s .co m * * Sample dynamic json format: * * { "0": {// A jsonObject}, "1": {// A jsonObject}, "2": {// A jsonObject} } * OR * { "0": [// A jsonArray], "1": [// A jsonArray], "2": [// A jsonArray] } * OR * { "0": value, "1": value, "2": value } * * @param classModel The mapped class. * @param jsonObject The JSON object response. * @return Returns a map array containing key-value pair. */ public static <E> Map<String, E> parseIntoMap(Class<E> classModel, JSONObject jsonObject) { Map<String, E> map = new HashMap<>(); Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); try { if (jsonObject.get(key) instanceof JSONObject) { map.put(key, parse(classModel, jsonObject.getJSONObject(key))); } else { map.put(key, classModel.cast(jsonObject.get(key))); } } catch (JSONException e) { e.printStackTrace(); } } return map; }
From source file:mondrian.xmla.impl.Olap4jXmlaServlet.java
/** * Unwraps a given interface from a given connection. * * @param connection Connection object//from w w w. j a v a 2 s . c o m * @param clazz Interface to unwrap * @param <T> Type of interface * @return Unwrapped object; never null * @throws java.sql.SQLException if cannot convert */ private static <T> T unwrap(Connection connection, Class<T> clazz) throws SQLException { // Invoke Wrapper.unwrap(). Works for JDK 1.6 and later, but we use // reflection so that it compiles on JDK 1.5. try { final Class<?> wrapperClass = Class.forName("java.sql.Wrapper"); if (wrapperClass.isInstance(connection)) { Method unwrapMethod = wrapperClass.getMethod("unwrap"); return clazz.cast(unwrapMethod.invoke(connection, clazz)); } } catch (ClassNotFoundException e) { // ignore } catch (NoSuchMethodException e) { // ignore } catch (InvocationTargetException e) { // ignore } catch (IllegalAccessException e) { // ignore } if (connection instanceof OlapWrapper) { OlapWrapper olapWrapper = (OlapWrapper) connection; return olapWrapper.unwrap(clazz); } throw new SQLException("not an instance"); }
From source file:info.novatec.testit.livingdoc.util.ClassUtils.java
public static <C> C createInstanceFromClassNameWithArguments(ClassLoader classLoader, String classWithArguments, Class<C> expectedType) throws UndeclaredThrowableException { try {//from ww w. j a v a 2s . co m List<String> parameters = toList(escapeValues(classWithArguments.split(";"))); Class<?> klass = ClassUtils.loadClass(classLoader, shift(parameters)); if (!expectedType.isAssignableFrom(klass)) { throw new IllegalArgumentException( "Class " + expectedType.getName() + " is not assignable from " + klass.getName()); } if (parameters.size() == 0) { return expectedType.cast(klass.newInstance()); } String[] args = parameters.toArray(new String[parameters.size()]); Constructor<?> constructor = klass.getConstructor(args.getClass()); return expectedType.cast(constructor.newInstance(new Object[] { args })); } catch (ClassNotFoundException e) { throw new UndeclaredThrowableException(e); } catch (InstantiationException e) { throw new UndeclaredThrowableException(e); } catch (IllegalAccessException e) { throw new UndeclaredThrowableException(e); } catch (NoSuchMethodException e) { throw new UndeclaredThrowableException(e); } catch (InvocationTargetException e) { throw new UndeclaredThrowableException(e); } }
From source file:com.xtructure.xutil.Range.java
/** * A utility to parse ranges./* ww w. java2s .c o m*/ * * @param <T> the generic type * @param text the text to parse * @param rangeType the type of endpoint of the range to parse * @return a parsed range * @throws Exception the exception */ public static final <T extends Comparable<T>> Range<T> parseRange(final String text, final Class<T> rangeType) throws Exception { final TextFormat<T> textFormat = TextFormat.getInstance(rangeType); if (textFormat == null) { throw new Exception(String.format("no text format for type %s (location %s)", rangeType, text)); } final Matcher matcher = RANGE_PATTERN.matcher(text); final String minStr = (matcher.matches() ? matcher.group(1) : text); final String maxStr = (matcher.matches() ? matcher.group(2) : text); if (String.class.equals(rangeType)) { return new Range<T>(rangeType.cast(minStr), rangeType.cast(maxStr)); } final T min = (minStr.equals("*") ? null : textFormat.parse(minStr)); final T max = (maxStr.equals("*") ? null : textFormat.parse(maxStr)); return new Range<T>(min, max); }
From source file:com.startechup.tools.ModelParser.java
/** * Gets the values from the {@link JSONArray JSONArrays}/response return from an api call * request and assign it to the field inside the class that will contain the parsed values. * * @param objectType The type of object that the List will contain. * @param jsonArray The API response object. * @return Returns an List with a generic type parameter. *///w w w.j a v a2s . co m public static <E> List<E> parse(Class<E> objectType, JSONArray jsonArray) { List<E> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { Object value = getValueFromJsonArray(jsonArray, i); if (value instanceof JSONObject) { JSONObject jsonObject = (JSONObject) value; list.add(parse(objectType, jsonObject)); } else if (value instanceof Number) { Object castedObject = castNumberObject(objectType, value); list.add(objectType.cast(castedObject)); } else { list.add(objectType.cast(value)); } } return list; }
From source file:de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.java
public static <T extends FeatureStructure> T selectByAddr(CAS aCas, Class<T> aType, int aAddress) { return aType.cast(aCas.getLowLevelCAS().ll_getFSForRef(aAddress)); }
From source file:de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.java
public static <T extends FeatureStructure> T selectByAddr(JCas aJCas, Class<T> aType, int aAddress) { return aType.cast(aJCas.getLowLevelCas().ll_getFSForRef(aAddress)); }
From source file:com.ctriposs.r2.transport.http.client.HttpClientFactory.java
private static <T> T coerce(String key, Object value, Class<T> valueClass) { if (value == null) { return null; }//from w ww .j av a 2s .c om if (!valueClass.isInstance(value)) { throw new IllegalArgumentException("Property " + key + " is of type " + value.getClass().getName() + " but must be " + valueClass.getName()); } return valueClass.cast(value); }