List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:Main.java
public static <T> T deserialize(Class<T> res, InputStream is) throws JAXBException { String pkg = res.getPackage().getName(); JAXBContext jc = getCachedContext(pkg); Unmarshaller u = jc.createUnmarshaller(); u.setEventHandler(new DefaultValidationEventHandler()); return res.cast(u.unmarshal(is)); }
From source file:gr.demokritos.iit.textforms.TextForm.java
/** * Get an instance of the correct subclass - the subclass that can parse the * JSON. If an error is encountered it throws an exception like specified * below./*from www . ja v a 2s .c om*/ * * @param data, the data representing the text object * @param classname, the class - subclass of TextForm to use to parse * the format. Will cal fromFormat of that class. * @return An instance of the class that parses the JSON * @throws gr.demokritos.iit.textforms.TextForm.InvalidFormatException */ public static TextForm fromFormat(String data, Class classname) throws InvalidFormatException { try { Class<? extends TextForm> textform = classname.asSubclass(TextForm.class); Method fromFormat = textform.getMethod("fromFormat", String.class); return textform.cast(fromFormat.invoke(null, data)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { if (!API.mapping.containsValue(classname)) { Logger.getLogger(TextForm.class.getName()).log(Level.SEVERE, "fromFormat generics expects one of the " + "following values {0}", API.mapping.values().toString()); } Logger.getLogger(TextForm.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:Main.java
/** * Gets the {@code sun.misc.Unsafe} instance, or {@code null} if not available on this platform. *///from w w w . ja v a2 s .com private static sun.misc.Unsafe getUnsafe() { sun.misc.Unsafe unsafe = null; try { unsafe = AccessController.doPrivileged(new PrivilegedExceptionAction<Unsafe>() { @Override public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) { return k.cast(x); } } // The sun.misc.Unsafe field does not exist. return null; } }); } catch (Throwable e) { // Catching Throwable here due to the fact that Google AppEngine raises NoClassDefFoundError // for Unsafe. } return unsafe; }
From source file:com.qualogy.qafe.business.integration.adapter.MappingAdapter.java
private static Object adaptToJavaObject(String mappingId, String attributeName, Object result, Object valueToAdapt, ClassLoader classLoader) { try {/*from w w w.jav a2 s .c o m*/ if (valueToAdapt != null) { Class resultClazz = classLoader.loadClass(result.getClass().getName()); Field field = resultClazz.getDeclaredField(attributeName); field.setAccessible(true); String fieldName = field.getType().getName(); String valueName = valueToAdapt.getClass().getName(); logger.info(field.getType().getName()); if (!fieldName.equals(valueName)) { if (PredefinedClassTypeConverter.isPredefined(field.getType())) valueToAdapt = PredefinedAdapterFactory.create(field.getType()).convert(valueToAdapt); else throw new IllegalArgumentException("Object passed [" + valueToAdapt + "] cannot be converted to type wanted[" + field.getType() + "] for field[" + field.getName() + "] in adapter[" + mappingId + "]"); } else { if (!PredefinedClassTypeConverter.isPredefined(field.getType())) { Class paramClazz = classLoader.loadClass(fieldName); valueToAdapt = paramClazz.cast(valueToAdapt); } } field.set(result, valueToAdapt); } } catch (IllegalArgumentException e) { throw new UnableToAdaptException( "arg [" + valueToAdapt + "] is illegal for field with name [" + attributeName + "]", e); } catch (SecurityException e) { throw new UnableToAdaptException(e); } catch (IllegalAccessException e) { throw new UnableToAdaptException( "field [" + attributeName + "] does not accessible on class [" + result.getClass() + "]", e); } catch (NoSuchFieldException e) { logger.log(Level.WARNING, "field [" + attributeName + "] does not exist on class [" + result.getClass() + "]", e); } catch (ClassNotFoundException e) { throw new UnableToAdaptException( "field [" + attributeName + "] class not found [" + result.getClass() + "]", e); } return result; }
From source file:Main.java
/** * Extracts the {@link Element} for the given name from the parent. * //ww w . j a va 2s. c o m * @param parent * @param name * @return */ public static <T extends Node> T findNode(Node parent, Class<T> type, String name) { final NodeList childNodes = parent.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Node child = childNodes.item(i); if (type.isAssignableFrom(child.getClass()) && name.equals(child.getNodeName())) { return type.cast(child); } } return null; }
From source file:me.tfeng.play.mongodb.MongoDbTypeConverter.java
public static <S, T> S convertToMongoDbType(Class<S> mongoClass, T data) { if (data == null) { return null; } else if (mongoClass.isInstance(data)) { return mongoClass.cast(data); } else {/*from ww w. ja va 2 s.c o m*/ @SuppressWarnings("unchecked") Converter<S, T> converter = (Converter<S, T>) CONVERTER_MAP .get(ImmutablePair.of(mongoClass, data.getClass())); if (converter != null) { return converter.convertToMongoDbType(data); } else if (DBObject.class.isAssignableFrom(mongoClass) && data instanceof String) { return mongoClass.cast(JSON.parse((String) data)); } else { return null; } } }
From source file:me.tfeng.play.mongodb.MongoDbTypeConverter.java
public static <S, T> T convertFromMongoDbType(Class<T> dataClass, S object) { if (object == null) { return null; } else if (dataClass.isInstance(object)) { return dataClass.cast(object); } else {/*from w ww . j ava2 s .c o m*/ @SuppressWarnings("unchecked") Converter<S, T> converter = (Converter<S, T>) CONVERTER_MAP .get(ImmutablePair.of(object.getClass(), dataClass)); if (converter != null) { return converter.convertFromMongoDbType(object); } else if (String.class.isAssignableFrom(dataClass) && object instanceof DBObject) { return dataClass.cast(JSON.serialize(object)); } else { return null; } } }
From source file:com.comichentai.serialize.SerializeUtil.java
public static <T> T deserialize(byte[] bytes, Class<T> clazz) { ByteArrayInputStream bais = null; ObjectInputStream ois = null; try {//from w w w . j a v a 2 s . c o m bais = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bais); Object object = ois.readObject(); return clazz.cast(object); } catch (Exception e) { throw new RuntimeException(e); } finally { closeQuietly(bais); closeQuietly(ois); } }
From source file:Utils.java
/** * Create a typesafe copy of a raw set.//from w ww. ja va2s . c om * @param rawSet an unchecked set * @param type the desired supertype of the entries * @param strict true to throw a <code>ClassCastException</code> if the raw set has an invalid entry, * false to skip over such entries (warnings may be logged) * @return a typed set guaranteed to contain only entries assignable * to the named type (or they may be null) * @throws ClassCastException if some entry in the raw set was not well-typed, and only if <code>strict</code> was true */ public static <E> Set<E> checkedSetByCopy(Set rawSet, Class<E> type, boolean strict) throws ClassCastException { Set<E> s = new HashSet<E>(rawSet.size() * 4 / 3 + 1); Iterator it = rawSet.iterator(); while (it.hasNext()) { Object e = it.next(); try { s.add(type.cast(e)); } catch (ClassCastException x) { if (strict) { throw x; } else { System.out.println("not assignable "); } } } return s; }
From source file:Main.java
public static <T extends Object> T[] extendModel(ListModel selected, T[] extras, Class<T> type) { int selectedSize = selected.getSize(); int extraSize = extras.length; @SuppressWarnings("unchecked") T[] augmented = (T[]) Array.newInstance(type, selectedSize + extraSize); // copy current for (int i = 0; i < selectedSize; i++) { augmented[i] = type.cast(selected.getElementAt(i)); }//from www .j a v a 2s.c om // augment for (int i = 0; i < extraSize; i++) { augmented[selectedSize + i] = extras[i]; } return augmented; }