List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:com.codelanx.codelanxlib.config.Config.java
/** * Attempts to return the {@link Config} value as a casted type. If the * value cannot be casted it will attempt to return the default value. If * the default value is inappropriate for the class, the method will * throw a {@link ClassCastException}./*from w ww . j av a 2 s .com*/ * * @since 0.1.0 * @version 0.1.0 * * @param <T> The type of the casting class * @param c The class type to cast to * @return A casted value, or {@code null} if unable to cast. If the passed * class parameter is of a primitive type or autoboxed primitive, * then a casted value of -1 is returned, or {@code false} for * booleans. If the passed class parameter is for {@link String}, * then {@link Object#toString()} is called on the value instead */ default public <T> T as(Class<T> c) { Validate.notNull(c, "Cannot cast to null"); Validate.isTrue(Primitives.unwrap(c) != void.class, "Cannot cast to a void type"); boolean primitive = Primitives.isWrapperType(c) || Primitives.isWrapperType(Primitives.wrap(c)); Object o = this.get(); if (primitive) { T back; if (o == null) { return Reflections.defaultPrimitiveValue(c); } else { back = Primitives.wrap(c).cast(o); } return back; } if (o == null) { return null; } if (c == String.class) { return (T) String.valueOf(o); } if (c.isInstance(o)) { return c.cast(o); } if (c.isInstance(this.getDefault())) { return c.cast(this.getDefault()); } throw new ClassCastException("Unable to cast config value"); }
From source file:com.netflix.client.config.DefaultClientConfigImpl.java
@SuppressWarnings("unchecked") @Override//from w w w .j a v a2s. c o m public <T> T get(IClientConfigKey<T> key) { Object obj = getProperty(key.key()); if (obj == null) { return null; } Class<T> type = key.type(); try { return type.cast(obj); } catch (ClassCastException e) { if (obj instanceof String) { String stringValue = (String) obj; if (Integer.class.equals(type)) { return (T) Integer.valueOf(stringValue); } else if (Boolean.class.equals(type)) { return (T) Boolean.valueOf(stringValue); } else if (Float.class.equals(type)) { return (T) Float.valueOf(stringValue); } else if (Long.class.equals(type)) { return (T) Long.valueOf(stringValue); } else if (Double.class.equals(type)) { return (T) Double.valueOf(stringValue); } else if (TimeUnit.class.equals(type)) { return (T) TimeUnit.valueOf(stringValue); } throw new IllegalArgumentException("Unable to convert string value to desired type " + type); } else { throw e; } } }
From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java
public <T> T javascriptProxyForModule(Class<T> baseInterface, Class<?>... otherClasses) { Class<?>[] allClasses;//ww w . j a va 2s . c o m if (otherClasses.length == 0) { allClasses = new Class[] { baseInterface }; } else { allClasses = new Class[otherClasses.length + 1]; allClasses[0] = baseInterface; System.arraycopy(otherClasses, 0, allClasses, 1, otherClasses.length); } InvocationHandler h = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { mKirinHelper.jsMethod(method.getName(), (Object[]) args); return null; } }; Object proxy = Proxy.newProxyInstance(baseInterface.getClassLoader(), allClasses, h); return baseInterface.cast(proxy); }
From source file:fr.univlorraine.mondossierweb.views.windows.PreferencesApplicationWindow.java
/** * Cre une fentre d'dition des preferences applicative * @param prfrence diter/* ww w.j a va 2 s. c om*/ */ public PreferencesApplicationWindow(PreferencesApplication prefApp) { /* Style */ setModal(true); setResizable(false); setClosable(false); setWidth("50%"); /* Layout */ VerticalLayout layout = new VerticalLayout(); layout.setMargin(true); layout.setSpacing(true); layout.setWidth("100%"); setContent(layout); /* Titre */ setCaption(applicationContext.getMessage(NAME + ".title", null, getLocale())); /* Formulaire */ fieldGroup = new BeanFieldGroup<>(PreferencesApplication.class); fieldGroup.setItemDataSource(prefApp); fieldGroup.setFieldFactory(new FieldGroupFieldFactory() { private static final long serialVersionUID = 1L; @Override @SuppressWarnings("rawtypes") public <T extends Field> T createField(Class<?> dataType, Class<T> fieldType) { if (fieldType == NativeSelect.class) { final NativeSelect field = new NativeSelect(); field.addItem("true"); field.addItem("false"); field.setNullSelectionAllowed(false); field.setImmediate(true); //field.setValue(centre.getTemSrv()); field.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { field.setValue(event.getProperty().getValue()); } }); return fieldType.cast(field); } else { final TextField field = new TextField(); field.setImmediate(true); field.addTextChangeListener(new FieldEvents.TextChangeListener() { private static final long serialVersionUID = 1L; @Override public void textChange(TextChangeEvent event) { if (!field.isReadOnly()) { field.setValue(event.getText()); } } }); return fieldType.cast(field); } } }); FormLayout formLayout = new FormLayout(); formLayout.setSpacing(true); formLayout.setSizeUndefined(); formLayout.setWidth("100%"); for (String fieldName : CONF_APP_FIELDS_ORDER) { String caption = applicationContext.getMessage(NAME + ".confAppTable." + fieldName, null, getLocale()); //Si on est sur un parametre booleen if (fieldName.equals("valeur") && estUneValeurBooleenne(prefApp.getValeur())) { //On forme le nativeSelect Field<?> field = fieldGroup.buildAndBind(caption, fieldName, NativeSelect.class); formLayout.addComponent(field); } else { Field<?> field = fieldGroup.buildAndBind(caption, fieldName); if (field instanceof AbstractTextField) { ((AbstractTextField) field).setNullRepresentation(""); field.setWidth("100%"); } formLayout.addComponent(field); } } fieldGroup.getField("prefId").setReadOnly(prefApp.getPrefId() != null); fieldGroup.getField("prefDesc").setReadOnly(prefApp.getPrefDesc() != null); layout.addComponent(formLayout); /* Ajoute les boutons */ HorizontalLayout buttonsLayout = new HorizontalLayout(); buttonsLayout.setWidth(100, Unit.PERCENTAGE); buttonsLayout.setSpacing(true); buttonsLayout.setMargin(true); layout.addComponent(buttonsLayout); btnAnnuler = new Button(applicationContext.getMessage(NAME + ".btnAnnuler", null, getLocale()), FontAwesome.TIMES); btnAnnuler.addClickListener(e -> close()); buttonsLayout.addComponent(btnAnnuler); buttonsLayout.setComponentAlignment(btnAnnuler, Alignment.MIDDLE_LEFT); btnEnregistrer = new Button(applicationContext.getMessage(NAME + ".btnSave", null, getLocale()), FontAwesome.SAVE); btnEnregistrer.addStyleName(ValoTheme.BUTTON_PRIMARY); btnEnregistrer.addClickListener(e -> { try { /* Valide la saisie */ fieldGroup.commit(); /* Enregistre la conf saisie */ configController.saveAppParameter(prefApp); /* Ferme la fentre */ close(); } catch (CommitException ce) { } }); buttonsLayout.addComponent(btnEnregistrer); buttonsLayout.setComponentAlignment(btnEnregistrer, Alignment.MIDDLE_RIGHT); /* Centre la fentre */ center(); }
From source file:com.atlassian.jira.ComponentManager.java
/** * Returns all the components currently inside of Pico which are instances of the given class. * * @param clazz the class to search for. * @return a list containing all the instances of the passed class registered in JIRA's pico container. *//*from w w w.j a v a2s.c om*/ public static <T> List<T> getComponentsOfType(final Class<T> clazz) { final PicoContainer pico = getInstance().getContainer(); final List<ComponentAdapter<T>> adapters = pico.getComponentAdapters(clazz); if (adapters.isEmpty()) { return Collections.emptyList(); } else { final List<T> returnList = new ArrayList<T>(adapters.size()); for (final ComponentAdapter<T> adapter : adapters) { // remove cast when we go to a Java5 pico returnList.add(clazz.cast(adapter.getComponentInstance(pico))); } return Collections.unmodifiableList(returnList); } }
From source file:ca.sqlpower.sqlobject.SQLObject.java
@NonProperty public <T extends SPObject> List<T> getChildrenWithoutPopulating(Class<T> type) { List<T> children = new ArrayList<T>(); for (SQLObject child : getChildrenWithoutPopulating()) { if (type.isAssignableFrom(child.getClass())) { children.add(type.cast(child)); }/*from w w w.j a v a 2s .c o m*/ } return Collections.unmodifiableList(children); }
From source file:com.blazemeter.bamboo.plugin.api.HttpUtility.java
public <T, V> T response(String url, V data, Method method, Class<T> returnType, Class<V> dataType) { T returnObj = null;//from w ww . java 2 s . c om JSONObject jo = null; String output = null; HttpResponse response = null; try { response = httpResponse(url, data, method); if (response != null) { output = EntityUtils.toString(response.getEntity()); logger.info("Received object from server: " + output); if (output.isEmpty()) { throw new IOException(); } jo = new JSONObject(output); } } catch (IOException ioe) { logger.error("Received empty response from server: ", ioe); return null; } catch (JSONException e) { logger.error("ERROR decoding Json: ", e); returnType = (Class<T>) String.class; return returnType.cast(output); } try { returnObj = returnType.cast(jo); } catch (ClassCastException cce) { logger.error("Failed to parse response from server: ", cce); throw new RuntimeException(jo.toString()); } return returnObj; }
From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.DatareportsServiceImpl.java
public Predicate genDatePredicate(final Class clazz, final String getter, final boolean before, final String dateStr, final DateFormat dateFormat) { return new Predicate() { public boolean evaluate(Object o) { if (dateStr == null || "".equals(dateStr)) { return true; }/*from w w w . ja v a2 s .c o m*/ Date date; try { date = dateFormat.parse(dateStr); } catch (ParseException e) { return true; } if (date == null) { return true; } try { final Method m = GetterMethod.getGetter(clazz, getter); if (before) { return ((Date) m.invoke(clazz.cast(o))).before(date); } else { return ((Date) m.invoke(clazz.cast(o))).after(date); } } catch (Exception e) { logger.debug(FancyExceptionLogger.printException(e)); return true; } } }; }
From source file:com.keetip.versio.service.impl.VersioningServiceImpl.java
public <T extends Resource> Optional<T> getRevision(String projectName, String resourceName, Class<T> resourceClass, Integer revision) { Validate.notEmpty(projectName, "Project name is required"); Validate.notEmpty(resourceName, "Resource name is required"); //TODO1: resolve projectId from projectName UUID projectId = UUID.randomUUID(); Optional<ResourceKey> key = resolveKey(projectId, resourceName); Optional<Resource> resourceHolder = null; if (!key.isPresent()) { Collection<Resource> allRevisions = mResourceProvider.getRevisions(projectId, resourceName); } else {/*from www . j av a 2s.co m*/ } if (!key.isPresent()) { resourceHolder = tryLoadResource(key.get(), projectId, resourceName); } else { resourceHolder = getLatestRevision(mResources.get(key.get())); } if (resourceHolder.isPresent()) { Object resource = resourceHolder.get(); return Optional.of(resourceClass.cast(resource)); } return Optional.absent(); }
From source file:com.slytechs.capture.FileFactory.java
public <T extends FileCapture<? extends FilePacket>> T openFile(final Class<T> type, final File file, FileMode mode, Filter<ProtocolFilterTarget> filter) throws IOException, FileFormatException { if (logger.isDebugEnabled()) { logger.debug(//from w w w. jav a 2 s . co m file.getName() + ", type=" + type.getName() + (filter == null ? "" : ", filter=" + filter)); } FileCapture capture; if (type == PcapFile.class) { capture = new PcapFileCapture(file, mode, null); } else if (type == SnoopFile.class) { capture = new SnoopFileCapture(file, mode, null); } else { throw new FileFormatException("Unsupported file format type, " + type.getName()); } return type.cast(capture); }