List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:com.ery.ertc.estorm.util.JVM.java
/** * Load the implementation of UnixOperatingSystemMXBean for Oracle jvm and runs the desired method. * //from w w w . java2 s . c o m * @param mBeanMethodName * : method to run from the interface UnixOperatingSystemMXBean * @return the method result */ private Long runUnixMXBeanMethod(String mBeanMethodName) { Object unixos; Class<?> classRef; Method mBeanMethod; try { classRef = Class.forName("com.sun.management.UnixOperatingSystemMXBean"); if (classRef.isInstance(osMbean)) { mBeanMethod = classRef.getMethod(mBeanMethodName, new Class[0]); unixos = classRef.cast(osMbean); return (Long) mBeanMethod.invoke(unixos); } } catch (Exception e) { LOG.warn("Not able to load class or method for" + " com.sun.management.UnixOperatingSystemMXBean.", e); } return null; }
From source file:ch.digitalfondue.npjt.QueryType.java
@SuppressWarnings("unchecked") private static <T> AffectedRowCountAndKey<T> executeUpdateAndKeepKeys(String template, Method method, NamedParameterJdbcTemplate jdbc, SqlParameterSource parameters) { Class<T> keyClass = (Class<T>) ((ParameterizedType) method.getGenericReturnType()) .getActualTypeArguments()[0]; KeyHolder keyHolder = new GeneratedKeyHolder(); int result = jdbc.update(template, parameters, keyHolder); Map<String, Object> keys = keyHolder.getKeys(); Object key;//from ww w . ja va2 s .c o m if (keys.size() > 1) { AutoGeneratedKey spec = Objects.requireNonNull(method.getDeclaredAnnotation(AutoGeneratedKey.class), "more than one key for query " + template + ": annotation @AutoGeneratedKey required"); key = Objects.requireNonNull(keys.get(spec.value()), "the key with name " + spec.value() + " has returned null for query " + template + ": required a non null key"); } else if (Number.class.isAssignableFrom(keyClass)) { Class<? extends Number> c = (Class<? extends Number>) keyClass; return new AffectedRowCountAndKey<>(result, (T) NumberUtils.convertNumberToTargetClass(keyHolder.getKey(), c)); } else { key = keys.values().iterator().next(); } return new AffectedRowCountAndKey<>(result, keyClass.cast(key)); }
From source file:com.funambol.json.coredb.CoreDBServlet.java
private <T> T getAttribute(String attributeName, HttpServletRequest request, Class<T> clazz) { if (request != null && clazz != null) { Object attribute = request.getAttribute(attributeName); if (attribute != null && clazz.isAssignableFrom(attribute.getClass())) { return clazz.cast(attribute); }//from w w w .j ava 2 s . c om } return null; }
From source file:org.fcrepo.camel.karaf.KarafIT.java
private <T> T getOsgiService(final Class<T> type, final String filter, final long timeout) { try {// w ww . j a v a 2 s .co m final ServiceTracker tracker = new ServiceTracker(bundleContext, createFilter("(&(" + OBJECTCLASS + "=" + type.getName() + ")" + filter + ")"), null); tracker.open(true); final Object svc = type.cast(tracker.waitForService(timeout)); if (svc == null) { throw new RuntimeException("Gave up waiting for service " + filter); } return type.cast(svc); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid filter", e); } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:im.r_c.android.fusioncache.FusionCache.java
/** * Get value from disk cache./*from w w w . j a v a 2 s.co m*/ * <p> * Only called when {@link #mDiskCache} is not null. */ private <T> T getFromDiskLocked(String key, Class<T> clz) { // Already know mDiskCache != null here if (clz == String.class) { return clz.cast(mDiskCache.getString(key)); } else if (clz == JSONObject.class) { return clz.cast(mDiskCache.getJSONObject(key)); } else if (clz == JSONArray.class) { return clz.cast(mDiskCache.getJSONArray(key)); } else if (clz == byte[].class) { return clz.cast(mDiskCache.getBytes(key)); } else if (clz == Bitmap.class) { return clz.cast(mDiskCache.getBitmap(key)); } else if (clz == Drawable.class) { Context context = mAppContextRef.get(); if (context != null) { return clz.cast(mDiskCache.getDrawable(key, context.getResources())); } else { return clz.cast(mDiskCache.getDrawable(key)); } } else if (clz == Serializable.class) { return clz.cast(mDiskCache.getSerializable(key)); } return null; }
From source file:Main.java
public static <T extends Object, Result> Result callMethodCast(T receiver, Class<Result> resultClass, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (receiver == null || methodName == null) { return null; }//from ww w. jav a2 s .c om Class<?> cls = receiver.getClass(); Method toInvoke = null; do { Method[] methods = cls.getDeclaredMethods(); methodLoop: for (Method method : methods) { if (!methodName.equals(method.getName())) { continue; } Class<?>[] paramTypes = method.getParameterTypes(); if (args == null && paramTypes == null) { toInvoke = method; break; } else if (args == null || paramTypes == null || paramTypes.length != args.length) { continue; } for (int i = 0; i < args.length; ++i) { if (!paramTypes[i].isAssignableFrom(args[i].getClass())) { continue methodLoop; } } toInvoke = method; } } while (toInvoke == null && (cls = cls.getSuperclass()) != null); Result t; if (toInvoke != null) { boolean accessible = toInvoke.isAccessible(); toInvoke.setAccessible(true); if (resultClass != null) { t = resultClass.cast(toInvoke.invoke(receiver, args)); } else { toInvoke.invoke(receiver, args); t = null; } toInvoke.setAccessible(accessible); return t; } else { throw new NoSuchMethodException("Method " + methodName + " not found"); } }
From source file:edu.wisc.commons.httpclient.HttpParamsBean.java
private <T> T getTypedParameter(String name, T defaultValue, Class<T> type, Function<Object, T> parser) { final Object value = delegate.getParameter(name); //If null return default value if (value == null) { return defaultValue; }/*from w ww . jav a 2 s . c o m*/ //If already the right type just cast and return final Class<? extends Object> valueType = value.getClass(); if (type.isAssignableFrom(valueType)) { return type.cast(value); } //Try parsing the value to the desired type try { return parser.apply(value); } catch (Exception e) { final ClassCastException cce = new ClassCastException( "Cannot convert '" + value + "' of type " + valueType.getName() + " to " + type.getName()); cce.initCause(e); throw cce; } }
From source file:com.redhat.ipaas.api.v1.rest.DataManager.java
public void addToCache(ModelData modelData) { try {//www .j a v a 2s . co m Class<? extends WithId> clazz; clazz = getClass(modelData.getKind()); Cache<String, WithId> cache = caches.getCache(modelData.getKind().toLowerCase()); LOGGER.debug(modelData.getKind() + ":" + modelData.getData()); WithId entity = clazz.cast(mapper.readValue(modelData.getData(), clazz)); Optional<String> id = entity.getId(); String idVal; if (!id.isPresent()) { idVal = generatePK(cache); entity = entity.withId(idVal); } else { idVal = id.get(); } cache.put(idVal, entity); } catch (Exception e) { IPaasServerException.launderThrowable(e); } }
From source file:com.heliosapm.tsdblite.handlers.websock.WebSocketRequest.java
/** * Returns the value for the specified name * @param name The map key/*from ww w . j av a 2s. c o m*/ * @param type The expected type of the value * @return The value */ public <T> T getValue(final String name, final Class<T> type) { if (name == null || name.trim().isEmpty()) throw new IllegalArgumentException("The passed name was null or empty"); if (type == null) throw new IllegalArgumentException("The passed type was null"); final Object o = map.get(name.trim()); return o == null ? null : type.cast(o); }
From source file:com.medallia.tiny.ObjectProvider.java
/** * Get an object by annotation//from w w w.j a v a 2 s .com */ @SuppressWarnings("unchecked") public <X> X getByAnnotation(Class<? extends Annotation> annotation, Class<X> c) { Object o = annotationMap.get(annotation); if (o == null) LOG.warn("No object for annotation " + annotation + " in " + this); // We do a safe cast if possible here, since we do not know what type of object was used when registering return c.isPrimitive() ? (X) o : c.cast(o); }