List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:net.signalr.client.json.jackson.JacksonElement.java
@Override public <T> T unwrap(final Class<T> type) { if (type == null) { throw new IllegalArgumentException("Type must not be null"); }/*from w w w . j a v a2 s .c o m*/ return type.cast(_node); }
From source file:me.bayes.vertx.vest.VestApplication.java
public Application getPropertyValue(String key, Class<Application> clazz) { return clazz.cast(properties.get(key)); }
From source file:com.conwet.silbops.model.AbstractMapping.java
@Override public boolean equals(Object obj) { if (this == obj) { return true; }//from www. j av a2s.c o m Class<T> clazz = getThisType(); if (clazz.isInstance(obj)) { AbstractMapping<T> other = clazz.cast(obj); return attributes.equals(other.attributes); } return false; }
From source file:com.omertron.rottentomatoesapi.tools.ResponseBuilder.java
/** * Get the wrapper for the passed properties * * Will retry up to retry limit/*from w w w.jav a 2 s .co m*/ * * @param <T> * @param clazz * @param properties * @return * @throws RottenTomatoesException */ public <T extends AbstractJsonMapping> T getResponse(Class<T> clazz, Map<String, String> properties) throws RottenTomatoesException { String url = ApiBuilder.create(properties); try { T wrapper = clazz.cast(MAPPER.readValue(getContent(url), clazz)); int retry = 1; while (!wrapper.isValid() && "Account Over Queries Per Second Limit".equalsIgnoreCase(wrapper.getError()) && retry <= retryLimit) { LOG.trace("Account over queries limit, waiting for {}ms.", retryDelay * retry); sleeper(retry++); wrapper = MAPPER.readValue(getContent(url), clazz); } if (wrapper.isValid()) { return wrapper; } else { throw new RottenTomatoesException(ApiExceptionType.MAPPING_FAILED, wrapper.getError(), url); } } catch (IOException ex) { throw new RottenTomatoesException(ApiExceptionType.MAPPING_FAILED, "Failed to map response", url, ex); } }
From source file:hudson.util.PersistedList.java
/** * Gets all instances that matches the given type. *///from w w w.ja v a2s.c om public <U extends T> List<U> getAll(Class<U> type) { List<U> r = new ArrayList<U>(); for (T t : data) if (type.isInstance(t)) r.add(type.cast(t)); return r; }
From source file:newcontroller.handler.impl.DefaultRequest.java
@Override public <T> T body(Class<T> clazz) { MediaType mediaType = MediaType.parseMediaType(this.request.getContentType()); HttpMessageConverter converter = HttpMessageConvertersHelper.findConverter(this.converters, clazz, mediaType);//from w w w . ja v a2 s . c om try { return clazz.cast(converter.read(clazz, new ServletServerHttpRequest(this.request))); } catch (IOException e) { throw new UncheckedIOException(e); // TODO } }
From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java
@SuppressWarnings("unchecked") public static <T> Optional<T> tryCast(Object val, final Class<T> expected) { if (val == null) { return Optional.empty(); }/* w ww . j a va 2 s.c o m*/ if (expected == null) { throw new IllegalArgumentException("Must provide an expected class!"); } if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) { return tryCast(((BaseValue<?>) val).get(), expected); } if (val instanceof Supplier) { Supplier<?> fun = (Supplier<?>) val; return tryCast(fun.get(), expected); } if (Text.class.isAssignableFrom(expected)) { if (val instanceof Text) { return TypeUtils.tryOptional(() -> expected.cast(val)); } else { if (val instanceof ItemStack) { return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val))); } if (val instanceof Instant) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(PlaceholderAPIPlugin.getInstance().formatter() .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault()))))); } if (val instanceof Duration) { String dur = formatDuration((Duration) val); return TypeUtils .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur))); } if (val instanceof LocalDateTime) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize( PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val)))); } if (val instanceof CommandSource) { return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE .deserialize(String.valueOf(((CommandSource) val).getName())))); } if (val.getClass().isArray()) { List<Text> l2 = unboxPrimitiveArray(val).stream() .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } if (val instanceof Iterable) { Iterable<?> l = (Iterable<?>) val; // should be safe cause we already checked assignability @SuppressWarnings("serial") final List<Text> l2 = new ArrayList<Object>() { { for (Object o : l) { add(o); } } }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional()) .collect(Collectors.toList()); return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2))); } return TypeUtils.tryOptional( () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val)))); } } if (val instanceof String) { if (String.class.isAssignableFrom(expected)) { return tryOptional(() -> expected.cast(val)); } if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(new String[] { v })); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(x)); } if (List.class.isAssignableFrom(expected) && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) { String v = (String) val; if (v.isEmpty()) { return Optional.empty(); } if (!v.contains("_")) { return tryOptional(() -> expected.cast(Collections.singletonList(v))); } String[] x = v.split("_"); if (x.length == 0) { return Optional.empty(); } boolean ne = false; for (String s : x) { ne = ne || !s.isEmpty(); } if (!ne) { return Optional.empty(); } return tryOptional(() -> expected.cast(Arrays.asList(x))); } Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected)); if (opt.isPresent()) { return opt; } opt = deserializers.entrySet().stream() .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected)) .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val))) .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o))); if (opt.isPresent()) { return opt; } try { // should theoretically match any string -> object conversions, such as deser // for now im filtering against method names as well just to avoid issues where // expected result is not obtained due to weird methods, might change in future Method method = Arrays.stream(expected.getDeclaredMethods()) .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class))) .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class)) .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no Object valout = method.invoke(null, (String) val); if (valout == null) { return Optional.empty(); } if (expected.isInstance(valout)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { return expected.cast(mh.invokeExact((String) val)); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(valout)); } if (valout instanceof Optional) { Optional<?> valopt = (Optional<?>) valout; if (!valopt.isPresent()) { return Optional.empty(); } Object v = valopt.get(); if (expected.isInstance(v)) { // Register a new deserializer once we confirm it works. Should prevent // extremely long parsing from happening multiple times. final MethodHandle mh = MethodHandles.publicLookup().unreflect(method); PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> { try { Optional<?> optx = (Optional<?>) mh.invokeExact((String) val); return expected.cast(optx.get()); } catch (Throwable e1) { throw new RuntimeException(e1); } }); return tryOptional(() -> expected.cast(v)); } else { return Optional.empty(); } } return Optional.empty(); } catch (Exception e) { // fires if no method found, if invoke throws, if something else goes wrong return Optional.empty(); } } return TypeUtils.tryOptional(() -> expected.cast(val)); }
From source file:com.thoughtworks.go.config.RolesConfig.java
private <T> List<T> filterRolesBy(Class<T> type) { List<T> rolesConfig = new ArrayList<>(); for (Role role : this) { if (role.getClass() == type) { rolesConfig.add(type.cast(role)); }/* w ww . j a v a 2 s. com*/ } return rolesConfig; }
From source file:com.orchestra.portale.controller.EditDeepeningPageController.java
@RequestMapping(value = "/editdpage", params = "id") public ModelAndView editPoibyID(@RequestParam(value = "id") String id) { ModelAndView model = new ModelAndView("editdpageform"); try {//from ww w . j a v a 2s . c o m DeepeningPage poi = pm.findDeepeningPage(id); 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 pagina d'approfondimento con id: " + id); return model2; } }
From source file:com.shigengyu.hyperion.core.WorkflowContextXmlSerializer.java
@Override public <T extends WorkflowContext> T deserialize(final Class<T> clazz, final String input) { T workflowContext = null;/*from www . j a va 2 s .c o m*/ try { Object deserializedObject = xStream.fromXML(input); if (deserializedObject == null) { return null; } workflowContext = clazz.cast(deserializedObject); // Initialize fields as default constructor will not be called when object is deserialized workflowContext.initializeFieldsOnDeserialization(); return workflowContext; } catch (ClassCastException e) { if (workflowContext != null) { throw new WorkflowContextException("Unable to cast workflow context of type [" + workflowContext.getClass().getName() + "] to [" + clazz.getName() + "]"); } else { throw new WorkflowContextException(e); } } }