List of usage examples for java.lang Class cast
@SuppressWarnings("unchecked") @HotSpotIntrinsicCandidate public T cast(Object obj)
From source file:org.opencb.commons.datastore.core.ObjectMap.java
protected <N extends Number> List<N> getAsNumberList(String field, Class<N> clazz, Function<String, N> parser, String separator) {//from w w w.j a v a 2 s . co m List list = getAsList(field, separator); if (list.isEmpty()) { List<N> emptyList = Collections.<N>emptyList(); put(field, emptyList); return emptyList; } else { boolean valid = true; for (Object o : list) { if (!clazz.isInstance(o)) { valid = false; break; } } if (valid) { return list; } else { List<N> numericList = new ArrayList<>(list.size()); for (Object o : list) { if (clazz.isInstance(o)) { numericList.add(clazz.cast(o)); } else { numericList.add(parser.apply(o.toString())); } } return numericList; } } }
From source file:com.cloudbees.plugins.credentials.CredentialsProvider.java
/** * Make a best effort to ensure that the supplied credential is a snapshot credential (i.e. self-contained and * does not reference any external stores) * * @param clazz the type of credential that we are trying to snapshot (specified so that if there is more than * one type of snapshot able credential interface implemented by the credentials, * then they can be separated out. * @param credential the credential.//from w ww .ja va2 s .co m * @param <C> the type of credential. * @return the credential or a snapshot of the credential. * @since 1.14 */ @SuppressWarnings("unchecked") public static <C extends Credentials> C snapshot(Class<C> clazz, C credential) { Class bestType = null; CredentialsSnapshotTaker bestTaker = null; for (CredentialsSnapshotTaker taker : ExtensionList.lookup(CredentialsSnapshotTaker.class)) { if (clazz.isAssignableFrom(taker.type()) && taker.type().isInstance(credential)) { if (bestTaker == null || bestType.isAssignableFrom(taker.type())) { bestTaker = taker; bestType = taker.type(); } } } if (bestTaker == null) { return credential; } return clazz.cast(bestTaker.snapshot(credential)); }
From source file:com.teotigraphix.caustk.sound.SoundSource.java
@SuppressWarnings("unchecked") @Override//from w w w. j a v a 2 s . c o m public <T extends Tone> T createTone(int index, String name, Class<? extends Tone> toneClass) throws CausticException { T tone = null; try { Constructor<? extends Tone> constructor = toneClass.getConstructor(ICaustkController.class); tone = (T) constructor.newInstance(getController()); initializeTone(tone, name, tone.getToneType(), index); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } SoundSourceUtils.setup(toneClass.cast(tone)); RackMessage.CREATE.send(getController(), tone.getToneType().getValue(), tone.getName(), tone.getIndex()); toneAdd(index, tone); return tone; }
From source file:com.haulmont.cuba.web.gui.components.WebLookupField.java
@Override public <T> void setOptionIconProvider(Class<T> optionClass, OptionIconProvider<T> optionIconProvider) { if (this.optionIconProvider != optionIconProvider) { // noinspection unchecked this.optionIconProvider = optionIconProvider; if (optionIconProvider == null) { component.setOptionIconProvider(null); } else {/*w w w. j a v a 2 s . c o m*/ component.setOptionIconProvider(itemId -> { T typedItem = optionClass.cast(itemId); String resourceId; try { // noinspection unchecked resourceId = optionIconProvider.getItemIcon(typedItem); } catch (Exception e) { LoggerFactory.getLogger(WebLookupField.class) .warn("Error invoking OptionIconProvider getItemIcon method", e); return null; } return WebComponentsHelper.getIcon(resourceId); }); } } }
From source file:org.openmrs.calculation.CalculationUtil.java
/** * Utility method that casts the specified value to the specified Type and handles conversions * to primitive wrapper classes in a better/more lenient way than java's type casting. Note that * the method will throw a {@link ConversionException} at runtime if it fails to convert the * specified value//from w w w . jav a 2 s. c om * * @see ConversionException * @param valueToCast the value to be cast * @param clazz the class to cast to * @return a value of the specified type * @should fail if the value to convert is not of a compatible type * @should convert the value to the specified type if it is compatible * @should return null if the passed in value is null * @should convert a valid string value to Boolean * @should convert a character value to Character * @should convert a valid string value to Short * @should convert a valid string value to Integer * @should convert a valid string value to Long * @should convert a valid string value to Float * @should convert a valid string value to Double * @should convert a valid string value to Byte * @should convert a single character value to Short * @should convert a valid single character value to Integer * @should convert a valid single character value to Long * @should convert a result with an number value in the valid range to byte * @should convert a valid string to an enum constant * @should convert a valid string to a class object * @should convert a valid string to a Locale * @should format a date object to a string using the default date format */ @SuppressWarnings("unchecked") public static <T> T cast(Object value, Class<T> clazz) { if (value == null) return null; if (clazz == null) throw new IllegalArgumentException("The class to cast to cannot be null"); T castValue = null; // We should be able to convert any value to a String if (String.class.isAssignableFrom(clazz)) { if (Date.class.isAssignableFrom(value.getClass())) castValue = (T) Context.getDateFormat().format((Date) value); else castValue = (T) value.toString(); } else { //we should be able to convert strings to simple types like String "2" to integer 2, //enums, dates, etc. Java types casting doesn't allow this so we need to transform the value first to //a string. BeanUtils from old spring versions doesn't consider enums as simple types if (BeanUtils.isSimpleValueType(clazz) || clazz.isEnum()) { try { String stringValue = null; //objects of types like date and Class whose toString methods are not reliable if (String.class.isAssignableFrom(value.getClass())) stringValue = (String) value; else stringValue = value.toString(); if (Character.class.equals(clazz) && stringValue.length() == 1) { value = stringValue.charAt(0); } else if (Locale.class.isAssignableFrom(clazz)) { return (T) LocaleUtility.fromSpecification(stringValue); } else if (Class.class.isAssignableFrom(clazz)) { return (T) Context.loadClass(stringValue); } else { Method method = clazz.getMethod("valueOf", new Class<?>[] { String.class }); value = method.invoke(null, stringValue); } } catch (Exception e) { //ignore and default to clazz.cast below } } try { castValue = clazz.cast(value); } catch (ClassCastException e) { throw new ConversionException(value, clazz); } } return castValue; }
From source file:io.sqp.client.impl.SqpConnectionImpl.java
private <T> CompletableFuture<T> getInformation(Class<T> infoType, InformationSubject subject, String detail) { CompletableFuture<T> future = new CompletableFuture<>(); if (!checkOpenAndNoErrors(future)) { return future; }/*from w ww. j ava 2 s . c o m*/ send(new InformationRequestMessage(subject, detail), new ResponseHandler<>(future, m -> { if (m.isA(MessageType.ReadyMessage)) { return false; // just ignore them } else if (m.isA(MessageType.InformationResponseMessage)) { InformationResponseMessage response = m.secureCast(); Object value = response.getValue(); if (!response.getResponseType().isCompatibleTo(infoType)) { future.completeExceptionally(new UnexpectedResultTypeException(value, infoType)); } else { future.complete(infoType.cast(value)); } return true; } throw new UnexpectedMessageException("waiting for information response", m); })); return future; }
From source file:com.liferay.ide.maven.core.LiferayMavenProjectProvider.java
@Override public <T> List<T> getData(String key, Class<T> type, Object... params) { List<T> retval = null;//ww w.j a va 2 s . c o m if ("profileIds".equals(key)) { final List<T> profileIds = new ArrayList<T>(); try { final List<Profile> profiles = MavenPlugin.getMaven().getSettings().getProfiles(); for (final Profile profile : profiles) { if (profile.getActivation() != null) { if (profile.getActivation().isActiveByDefault()) { continue; } } profileIds.add(type.cast(profile.getId())); } if (params[0] != null && params[0] instanceof File) { final File locationDir = (File) params[0]; File pomFile = new File(locationDir, IMavenConstants.POM_FILE_NAME); if (!pomFile.exists() && locationDir.getParentFile().exists()) { // try one level up for when user is adding new module pomFile = new File(locationDir.getParentFile(), IMavenConstants.POM_FILE_NAME); } if (pomFile.exists()) { final IMaven maven = MavenPlugin.getMaven(); Model model = maven.readModel(pomFile); File parentDir = pomFile.getParentFile(); while (model != null) { for (org.apache.maven.model.Profile p : model.getProfiles()) { profileIds.add(type.cast(p.getId())); } parentDir = parentDir.getParentFile(); if (parentDir != null && parentDir.exists()) { try { model = maven.readModel(new File(parentDir, IMavenConstants.POM_FILE_NAME)); } catch (Exception e) { model = null; } } } } } } catch (CoreException e) { LiferayMavenCore.logError(e); } retval = profileIds; } else if ("liferayVersions".equals(key)) { final List<T> possibleVersions = new ArrayList<T>(); final RepositorySystem system = AetherUtil.newRepositorySystem(); final RepositorySystemSession session = AetherUtil.newRepositorySystemSession(system); final String groupId = params[0].toString(); final String artifactId = params[1].toString(); final String coords = groupId + ":" + artifactId + ":[6,)"; final Artifact artifact = new DefaultArtifact(coords); final VersionRangeRequest rangeRequest = new VersionRangeRequest(); rangeRequest.setArtifact(artifact); rangeRequest.addRepository(AetherUtil.newCentralRepository()); rangeRequest.addRepository(AetherUtil.newLiferayRepository()); try { final VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest); final List<Version> versions = rangeResult.getVersions(); for (Version version : versions) { final String val = version.toString(); if (!"6.2.0".equals(val)) { possibleVersions.add(type.cast(val)); } } retval = possibleVersions; } catch (VersionRangeResolutionException e) { } } else if ("parentVersion".equals(key)) { final List<T> version = new ArrayList<T>(); final File locationDir = (File) params[0]; final File parentPom = new File(locationDir, IMavenConstants.POM_FILE_NAME); if (parentPom.exists()) { try { final IMaven maven = MavenPlugin.getMaven(); final Model model = maven.readModel(parentPom); version.add(type.cast(model.getVersion())); retval = version; } catch (CoreException e) { LiferayMavenCore.logError("unable to get parent version", e); } } } else if ("parentGroupId".equals(key)) { final List<T> groupId = new ArrayList<T>(); final File locationDir = (File) params[0]; final File parentPom = new File(locationDir, IMavenConstants.POM_FILE_NAME); if (parentPom.exists()) { try { final IMaven maven = MavenPlugin.getMaven(); final Model model = maven.readModel(parentPom); groupId.add(type.cast(model.getGroupId())); retval = groupId; } catch (CoreException e) { LiferayMavenCore.logError("unable to get parent groupId", e); } } } else if ("archetypeGAV".equals(key)) { final String frameworkType = (String) params[0]; final String value = LiferayMavenCore.getPreferenceString("archetype-gav-" + frameworkType, ""); retval = Collections.singletonList(type.cast(value)); } return retval; }
From source file:it.delli.mwebc.servlet.MWebCManager.java
private void updateServerWidget(Page page, JsonObject widgetProp) { Widget widget = page.getWidget(widgetProp.get("id").getAsString()); CastHelper castHelper = page.getApplication().getCastHelper(widget.getClass()); JsonArray data = widgetProp.get("data").getAsJsonArray(); for (int j = 0; j < data.size(); j++) { JsonObject itemData = data.get(j).getAsJsonObject(); Field fieldAttribute = ReflectionUtils.getAnnotatedField(widget.getClass(), itemData.get("attribute").getAsString(), WidgetAttribute.class); if (fieldAttribute != null) { fieldAttribute.setAccessible(true); Class<?> paramType = fieldAttribute.getType(); try { String value = null; if (itemData.get("value") == null || itemData.get("value") instanceof JsonNull) { value = null;// w w w. j a v a 2 s . c o m } else if (itemData.get("value") instanceof JsonArray) { JsonArray valueArray = (JsonArray) itemData.get("value"); ArrayList<String> tmp = new ArrayList<String>(); for (JsonElement jsonElement : valueArray) { tmp.add(jsonElement.getAsString()); } if (tmp.size() > 0) { value = StringUtils.join(tmp, ","); } else { value = null; } } else if (itemData.get("value") instanceof JsonObject) { value = itemData.get("value").toString(); } else { value = itemData.get("value").getAsString(); } fieldAttribute.setAccessible(true); fieldAttribute.set(widget, paramType.cast(castHelper.toType(value, paramType))); } catch (Exception e) { log.warn("Warning in updating server widgets attribute '" + itemData.get("attribute").getAsString() + "' for widget " + widget.getClass().getName(), e); } } else { log.warn("Warning in updating server widgets attribute. The attribute '" + itemData.get("attribute").getAsString() + "' doesn't exist for widget " + widget.getClass().getName()); } } }
From source file:com.github.yihtserns.jaxbean.unmarshaller.api.BlueprintBeanHandlerTest.java
private <T> T doUnmarshal(String blueprintXml, Class<T> rootType, Class<?>... otherTypes) throws Exception { File file = tempFolder.newFile(); FileUtils.write(file, blueprintXml); final String id = "bean"; final JaxbeanUnmarshaller unmarshaller = JaxbeanUnmarshaller.newInstance(merge(rootType, otherTypes)); final URI jaxbNamespaceUri = new URI("http://example.com/jaxb"); BlueprintContainerImpl blueprintContainer = new BlueprintContainerImpl(getClass().getClassLoader(), Arrays.asList(file.toURI().toURL()), false) { @Override// w w w .j a v a 2s .c om protected NamespaceHandlerSet createNamespaceHandlerSet() { SimpleNamespaceHandlerSet nsHandlerSet = (SimpleNamespaceHandlerSet) super.createNamespaceHandlerSet(); if (!nsHandlerSet.getNamespaces().contains(jaxbNamespaceUri)) { nsHandlerSet.addNamespace(jaxbNamespaceUri, null, new UnmarshallerNamespaceHandler(unmarshaller, id)); } return nsHandlerSet; } }; blueprintContainer.init(false); try { return rootType.cast(blueprintContainer.getComponentInstance(id)); } finally { blueprintContainer.destroy(); } }