List of usage examples for java.lang Number floatValue
public abstract float floatValue();
From source file:cc.aileron.accessor.TypeConvertorImpl.java
/** * default constractor//from w ww . j a v a 2s.c om */ @Inject public TypeConvertorImpl() { map.put(Boolean.TYPE, new C() { @Override public Boolean convert(final java.lang.Number number) { return number.intValue() != 0; } }); map.put(Byte.TYPE, new C() { @Override public Byte convert(final java.lang.Number number) { return number.byteValue(); } }); map.put(Short.TYPE, new C() { @Override public Short convert(final java.lang.Number number) { return number.shortValue(); } }); map.put(Integer.TYPE, new C() { @Override public Integer convert(final java.lang.Number number) { return number.intValue(); } }); map.put(Long.TYPE, new C() { @Override public Long convert(final java.lang.Number number) { return number.longValue(); } }); map.put(Float.TYPE, new C() { @Override public Float convert(final java.lang.Number number) { return number.floatValue(); } }); map.put(Double.TYPE, new C() { @Override public Double convert(final java.lang.Number number) { return number.doubleValue(); } }); }
From source file:com.xtructure.xevolution.genetics.impl.AbstractPopulation.java
/** * Adds the attribute in the given {@link Genome} with the given * {@link XValId} to the corresponding value in the accumulation map. * /*from ww w. java 2s . c o m*/ * @param <V> * the type of the attribute * @param valueId * the id of the attribute * @param accMap * the accumulation map * @param genome * the {@link Genome} from which to get the attribute */ private <V extends Comparable<V>> void updateAccMap(XValId<V> valueId, ValueMap accMap, Genome<D> genome) { getLogger().trace("begin %s.updateAccMap(%s, %s, %s)", getClass().getSimpleName(), valueId, accMap, genome); if (Number.class.isAssignableFrom(valueId.getType())) { if (accMap.get(valueId) == null) { accMap.set(// valueId, // genome.getAttribute(valueId)); } else { Number acc = (Number) accMap.get(valueId); Number nxt = (Number) genome.getAttribute(valueId); Number sum = null; ValueType type = ValueType.getValueType(valueId.getType()); if (type != null) { switch (type) { case DOUBLE: sum = acc.doubleValue() + nxt.doubleValue(); break; case FLOAT: sum = acc.floatValue() + nxt.floatValue(); break; case LONG: sum = acc.longValue() + nxt.longValue(); break; case INTEGER: sum = acc.intValue() + nxt.intValue(); break; case SHORT: sum = acc.shortValue() + nxt.shortValue(); break; case BYTE: sum = acc.byteValue() + nxt.byteValue(); break; default: break; } @SuppressWarnings("unchecked") V v = (V) sum; accMap.set(valueId, v); } } } getLogger().trace("end %s.updateAccMap()", getClass().getSimpleName()); }
From source file:org.pentaho.reporting.engine.classic.wizard.WizardProcessor.java
protected void setupDefaultGrid(final Band band, final Element detailElement) { setupDefaultPadding(band, detailElement); final ElementStyleSheet styleSheet = detailElement.getStyle(); // Always make the height of the detailElement dynamic to the band // According to thomas negative numbers equate to percentages styleSheet.setStyleProperty(ElementStyleKeys.MIN_HEIGHT, new Float(-100)); final Object maybeBorderStyle = band.getAttribute(AttributeNames.Wizard.NAMESPACE, AttributeNames.Wizard.GRID_STYLE); final Object maybeBorderWidth = band.getAttribute(AttributeNames.Wizard.NAMESPACE, AttributeNames.Wizard.GRID_WIDTH); final Object maybeBorderColor = band.getAttribute(AttributeNames.Wizard.NAMESPACE, AttributeNames.Wizard.GRID_COLOR); if (maybeBorderColor instanceof Color == false || maybeBorderStyle instanceof BorderStyle == false || maybeBorderWidth instanceof Number == false) { return;/*from w w w .j a va 2s . c o m*/ } final BorderStyle style = (BorderStyle) maybeBorderStyle; final Color color = (Color) maybeBorderColor; final Number number = (Number) maybeBorderWidth; final Float width = new Float(number.floatValue()); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_TOP_WIDTH, width); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_TOP_COLOR, color); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_TOP_STYLE, style); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_LEFT_WIDTH, width); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_LEFT_COLOR, color); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_LEFT_STYLE, style); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_BOTTOM_WIDTH, width); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_BOTTOM_COLOR, color); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_BOTTOM_STYLE, style); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_RIGHT_WIDTH, width); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_RIGHT_COLOR, color); styleSheet.setStyleProperty(ElementStyleKeys.BORDER_RIGHT_STYLE, style); }
From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java
private void compute(final Mask selectedMask) { final RasterDataNode raster = getRaster(); final AttributeDescriptor dataField = scatterPlotModel.dataField; if (raster == null || dataField == null) { return;// w w w.jav a 2 s .c om } SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() { @Override protected ComputedData[] doInBackground() throws Exception { SystemUtils.LOG.finest("start computing scatter plot data"); final List<ComputedData> computedDataList = new ArrayList<>(); final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource .getFeatureCollection(); final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]); final int boxSize = scatterPlotModel.boxSize; final Rectangle sceneRect = new Rectangle(raster.getRasterWidth(), raster.getRasterHeight()); final GeoCoding geoCoding = raster.getGeoCoding(); final AffineTransform imageToModelTransform; imageToModelTransform = Product.findImageToModelTransform(geoCoding); for (SimpleFeature feature : features) { final Point point = (Point) feature.getDefaultGeometryProperty().getValue(); Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY()); final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null); if (!sceneRect.contains(imagePos)) { continue; } final float imagePosX = (float) imagePos.getX(); final float imagePosY = (float) imagePos.getY(); final Rectangle imageRect = sceneRect.intersection(new Rectangle( ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize)); if (imageRect.isEmpty()) { continue; } final double[] rasterValues = new double[imageRect.width * imageRect.height]; raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues); final int[] maskBuffer = new int[imageRect.width * imageRect.height]; Arrays.fill(maskBuffer, 1); if (selectedMask != null) { selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, maskBuffer); } final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2); if (maskBuffer[centerIndex] == 0) { continue; } double sum = 0; double sumSqr = 0; int n = 0; boolean valid = false; for (int y = 0; y < imageRect.height; y++) { for (int x = 0; x < imageRect.width; x++) { final int index = y * imageRect.height + x; if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) { final double rasterValue = rasterValues[index]; sum += rasterValue; sumSqr += rasterValue * rasterValue; n++; valid = true; } } } if (!valid) { continue; } double rasterMean = sum / n; double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0; String localName = dataField.getLocalName(); Number attribute = (Number) feature.getAttribute(localName); final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties(); final float correlativeData = attribute.floatValue(); final GeoPos geoPos = new GeoPos(); if (geoCoding.canGetGeoPos()) { final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY); geoCoding.getGeoPos(pixelPos, geoPos); } else { geoPos.setInvalid(); } computedDataList.add( new ComputedData(imagePosX, imagePosY, (float) geoPos.getLat(), (float) geoPos.getLon(), (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties)); } return computedDataList.toArray(new ComputedData[computedDataList.size()]); } @Override public void done() { try { final ValueAxis xAxis = getPlot().getDomainAxis(); final ValueAxis yAxis = getPlot().getRangeAxis(); xAxis.setAutoRange(false); yAxis.setAutoRange(false); scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; final ComputedData[] data = get(); if (data.length == 0) { return; } computedDatas = data; final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName()); for (ComputedData computedData : computedDatas) { final float rasterMean = computedData.rasterMean; final float rasterSigma = computedData.rasterSigma; final float correlativeData = computedData.correlativeData; scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean, rasterMean - rasterSigma, rasterMean + rasterSigma); } computingData = true; scatterpointsDataset.addSeries(scatterValues); xAxis.setAutoRange(true); yAxis.setAutoRange(true); xAxis.setAutoRange(false); yAxis.setAutoRange(false); xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound()); yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound()); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(xAxis, 3); } else { xAxisRangeControl.adjustAxis(xAxis, 3); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(yAxis, 3); } else { yAxisRangeControl.adjustAxis(yAxis, 3); } computeRegressionAndAcceptableDeviationData(); computingData = false; } catch (InterruptedException | CancellationException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n" + "Calculation canceled.", JOptionPane.ERROR_MESSAGE, null); } catch (ExecutionException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n" + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null); } } }; swingWorker.execute(); }
From source file:de.tuberlin.uebb.jbop.optimizer.utils.NodeHelper.java
public static Number cast(final Number number, final AbstractInsnNode numberNode, final AbstractInsnNode castNode) { if (castNode == null) { return null; }//from w ww .j a v a 2s . c o m if (castNode == numberNode) { return number; } final int opcode = castNode.getOpcode(); if (opcode == I2B) { return (byte) number.intValue(); } // if(opcode==I2C) { // return (char)number.intValue(); // } if (opcode == I2L) { return (long) number.intValue(); } if (opcode == I2S) { return (short) number.intValue(); } if (opcode == I2D) { return (double) number.intValue(); } if (opcode == I2F) { return (float) number.intValue(); } if (opcode == D2F) { return (float) number.doubleValue(); } if (opcode == D2I) { return (int) number.doubleValue(); } if (opcode == D2L) { return (long) number.doubleValue(); } if (opcode == F2D) { return (double) number.floatValue(); } if (opcode == F2I) { return (int) number.floatValue(); } if (opcode == F2L) { return (long) number.floatValue(); } if (opcode == L2D) { return (long) number.longValue(); } if (opcode == L2F) { return (float) number.longValue(); } if (opcode == L2I) { return (int) number.longValue(); } return number; }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfLogicalPageDrawable.java
private Phrase createPhrase(final RenderableComplexText node) { Phrase p = new Phrase(); RichTextSpec text = node.getRichText(); for (RichTextSpec.StyledChunk c : text.getStyleChunks()) { TypedMapWrapper<Attribute, Object> attributes = new TypedMapWrapper<Attribute, Object>( c.getAttributes());//from w w w . j a v a 2 s . c o m final Number size = attributes.get(TextAttribute.SIZE, 10f, Number.class); final PdfTextSpec pdfTextSpec = computeFont(c); final int style = computeStyle(attributes, pdfTextSpec); final Color paint = (Color) c.getStyleSheet().getStyleProperty(ElementStyleKeys.PAINT); // add chunks BaseFont baseFont = pdfTextSpec.getFontMetrics().getBaseFont(); Font font = new Font(baseFont, size.floatValue(), style, paint); if (c.getOriginatingTextNode() instanceof RenderableReplacedContentBox) { RenderableReplacedContentBox content = (RenderableReplacedContentBox) c.getOriginatingTextNode(); com.lowagie.text.Image image = imageHandler.createImage(content); if (image != null) { Chunk chunk = new Chunk(image, 0, 0); // chunk.setFont(font); p.add(chunk); } } else { String textToPrint = c.getText(); Chunk chunk = new Chunk(textToPrint, font); p.add(chunk); } } return p; }
From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java
private void compute(final Mask selectedMask) { final RasterDataNode raster = getRaster(); final AttributeDescriptor dataField = scatterPlotModel.dataField; if (raster == null || dataField == null) { return;//from w w w. j a v a 2s . c o m } SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() { @Override protected ComputedData[] doInBackground() throws Exception { BeamLogManager.getSystemLogger().finest("start computing scatter plot data"); final List<ComputedData> computedDataList = new ArrayList<>(); final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource .getFeatureCollection(); final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]); final int boxSize = scatterPlotModel.boxSize; final Rectangle sceneRect = new Rectangle(raster.getSceneRasterWidth(), raster.getSceneRasterHeight()); final GeoCoding geoCoding = raster.getGeoCoding(); final AffineTransform imageToModelTransform; imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding); for (SimpleFeature feature : features) { final Point point = (Point) feature.getDefaultGeometryProperty().getValue(); Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY()); final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null); if (!sceneRect.contains(imagePos)) { continue; } final float imagePosX = (float) imagePos.getX(); final float imagePosY = (float) imagePos.getY(); final Rectangle imageRect = sceneRect.intersection(new Rectangle( ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize)); if (imageRect.isEmpty()) { continue; } final double[] rasterValues = new double[imageRect.width * imageRect.height]; raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues); final int[] maskBuffer = new int[imageRect.width * imageRect.height]; Arrays.fill(maskBuffer, 1); if (selectedMask != null) { selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, maskBuffer); } final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2); if (maskBuffer[centerIndex] == 0) { continue; } double sum = 0; double sumSqr = 0; int n = 0; boolean valid = false; for (int y = 0; y < imageRect.height; y++) { for (int x = 0; x < imageRect.width; x++) { final int index = y * imageRect.height + x; if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) { final double rasterValue = rasterValues[index]; sum += rasterValue; sumSqr += rasterValue * rasterValue; n++; valid = true; } } } if (!valid) { continue; } double rasterMean = sum / n; double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0; String localName = dataField.getLocalName(); Number attribute = (Number) feature.getAttribute(localName); final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties(); final float correlativeData = attribute.floatValue(); final GeoPos geoPos = new GeoPos(); if (geoCoding.canGetGeoPos()) { final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY); geoCoding.getGeoPos(pixelPos, geoPos); } else { geoPos.setInvalid(); } computedDataList.add(new ComputedData(imagePosX, imagePosY, geoPos.getLat(), geoPos.getLon(), (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties)); } return computedDataList.toArray(new ComputedData[computedDataList.size()]); } @Override public void done() { try { final ValueAxis xAxis = getPlot().getDomainAxis(); final ValueAxis yAxis = getPlot().getRangeAxis(); xAxis.setAutoRange(false); yAxis.setAutoRange(false); scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; final ComputedData[] data = get(); if (data.length == 0) { return; } computedDatas = data; final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName()); for (ComputedData computedData : computedDatas) { final float rasterMean = computedData.rasterMean; final float rasterSigma = computedData.rasterSigma; final float correlativeData = computedData.correlativeData; scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean, rasterMean - rasterSigma, rasterMean + rasterSigma); } computingData = true; scatterpointsDataset.addSeries(scatterValues); xAxis.setAutoRange(true); yAxis.setAutoRange(true); xAxis.setAutoRange(false); yAxis.setAutoRange(false); xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound()); yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound()); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(xAxis, 3); } else { xAxisRangeControl.adjustAxis(xAxis, 3); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(yAxis, 3); } else { yAxisRangeControl.adjustAxis(yAxis, 3); } computeRegressionAndAcceptableDeviationData(); computingData = false; } catch (InterruptedException | CancellationException e) { BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e); JOptionPane.showMessageDialog(getParentDialogContentPane(), "Failed to compute correlative plot.\n" + "Calculation canceled.", /*I18N*/ CHART_TITLE, /*I18N*/ JOptionPane.ERROR_MESSAGE); } catch (ExecutionException e) { BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e); JOptionPane.showMessageDialog(getParentDialogContentPane(), "Failed to compute correlative plot.\n" + "An error occurred:\n" + e.getCause().getMessage(), CHART_TITLE, /*I18N*/ JOptionPane.ERROR_MESSAGE); } } }; swingWorker.execute(); }
From source file:org.dcm4che.tool.dcm2jpg.Dcm2Jpg.java
public void initImageWriter(String formatName, String suffix, String clazz, String compressionType, Number quality) { Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(formatName); if (!imageWriters.hasNext()) throw new IllegalArgumentException( MessageFormat.format(rb.getString("formatNotSupported"), formatName)); this.suffix = suffix != null ? suffix : formatName.toLowerCase(); imageWriter = imageWriters.next();/*from w ww . ja v a 2s .c om*/ if (clazz != null) while (!clazz.equals(imageWriter.getClass().getName())) if (imageWriters.hasNext()) imageWriter = imageWriters.next(); else throw new IllegalArgumentException( MessageFormat.format(rb.getString("noSuchImageWriter"), clazz, formatName)); imageWriteParam = imageWriter.getDefaultWriteParam(); if (compressionType != null || quality != null) { imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); if (compressionType != null) imageWriteParam.setCompressionType(compressionType); if (quality != null) imageWriteParam.setCompressionQuality(quality.floatValue()); } }
From source file:com.jogden.spunkycharts.traditionalchart.TraditionalChartFragmentAdapter.java
private final void _setCallbacks() { this._priceSgmnt.setOnRemoveCallBack(new TraditionalChartPanel.CallBackOnRemove() { public void call(Number high, Number low) { float m = (_highPriceDsply - _lowPriceDsply) / (_highPrice - _lowPrice); _highPrice = high.floatValue(); _lowPrice = low.floatValue(); float actualDiff = (_highPrice - _lowPrice); float displayDiff = actualDiff * m; float midDiffDiff = (displayDiff - actualDiff) / 2; if ((_lowPriceDsply = _lowPrice - midDiffDiff) < 0) { _lowPriceDsply = 0;/*w w w .ja va 2s . co m*/ midDiffDiff = _lowPrice; } _highPriceDsply = _highPrice + midDiffDiff; _createPriceAxisY(); } }); this._volumeSgmnt.setOnRemoveCallBack(new TraditionalChartPanel.CallBackOnRemove() { public void call(Number high, Number low) { _highVolume = high.intValue(); _createVolumeAxis(); } }); }
From source file:weave.servlets.WeaveServlet.java
/** * Tries to convert value to the given type. * @param value The value to cast to a new type. * @param type The desired type.// w ww . j a va2 s .c om * @return The value, which may have been cast as the new type. */ protected Object cast(Object value, Class<?> type) throws RemoteException { if (type.isInstance(value)) return value; try { if (value == null) // null -> NaN { if (type == double.class || type == Double.class) value = Double.NaN; else if (type == float.class || type == Float.class) value = Float.NaN; return value; } if (value instanceof Map) // Map -> Java Bean { Object bean = type.newInstance(); for (Field field : type.getFields()) { Object fieldValue = ((Map<?, ?>) value).get(field.getName()); fieldValue = cast(fieldValue, field.getType()); field.set(bean, fieldValue); } return bean; } if (type.isArray()) // ? -> T[] { if (value instanceof String) // String -> String[] value = CSVParser.defaultParser.parseCSVRow((String) value, true); if (value instanceof List) // List -> Object[] value = ((List<?>) value).toArray(); if (value.getClass().isArray()) // T1[] -> T2[] { int n = Array.getLength(value); Class<?> itemType = type.getComponentType(); Object output = Array.newInstance(itemType, n); while (n-- > 0) Array.set(output, n, cast(Array.get(value, n), itemType)); return output; } } if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection> { value = cast(value, Object[].class); // ? -> Object[] if (value.getClass().isArray()) // T1[] -> Vector<T2> { int n = Array.getLength(value); List<Object> output = new Vector<Object>(n); TypeVariable<?>[] itemTypes = type.getTypeParameters(); Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null; while (n-- > 0) { Object item = Array.get(value, n); if (itemType != null) item = cast(item, itemType); // T1 -> T2 output.set(n, item); } return output; } } if (value instanceof String) // String -> ? { String string = (String) value; // String -> primitive if (type == char.class || type == Character.class) return string.charAt(0); if (type == byte.class || type == Byte.class) return Byte.parseByte(string); if (type == long.class || type == Long.class) return Long.parseLong(string); if (type == int.class || type == Integer.class) return Integer.parseInt(string); if (type == short.class || type == Short.class) return Short.parseShort(string); if (type == float.class || type == Float.class) return Float.parseFloat(string); if (type == double.class || type == Double.class) return Double.parseDouble(string); if (type == boolean.class || type == Boolean.class) return string.equalsIgnoreCase("true"); if (type == InputStream.class) // String -> InputStream { try { return new ByteArrayInputStream(string.getBytes("UTF-8")); } catch (Exception e) { return null; } } } if (value instanceof Number) // Number -> primitive { Number number = (Number) value; if (type == byte.class || type == Byte.class) return number.byteValue(); if (type == long.class || type == Long.class) return number.longValue(); if (type == int.class || type == Integer.class) return number.intValue(); if (type == short.class || type == Short.class) return number.shortValue(); if (type == float.class || type == Float.class) return number.floatValue(); if (type == double.class || type == Double.class) return number.doubleValue(); if (type == char.class || type == Character.class) return Character.toChars(number.intValue())[0]; if (type == boolean.class || type == Boolean.class) return !Double.isNaN(number.doubleValue()) && number.intValue() != 0; } } catch (Exception e) { throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(), type.getSimpleName()), e); } // Return original value if not handled above. // Primitives and their Object equivalents will cast automatically. return value; }