Example usage for java.lang Number getClass

List of usage examples for java.lang Number getClass

Introduction

In this page you can find the example usage for java.lang Number getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.lightadmin.core.util.NumberUtils.java

private static void raiseOverflowException(Number number, Class targetClass) {
    throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
            + number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
}

From source file:NumberUtils.java

/**
 * Raise an overflow exception for the given number and target class.
 * @param number the number we tried to convert
 * @param targetClass the target class we tried to convert to
 *//*from   w w  w .j a  va  2 s . co  m*/
private static void raiseOverflowException(Number number, Class targetClass) {
    throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
            + number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
}

From source file:NumberUtils.java

/**
 * Raise an overflow exception for the given number and target class.
 * @param number the number we tried to convert
 * @param targetClass the target class we tried to convert to
 *///from  w w  w.  ja  v  a 2 s  .c o  m
private static void raiseOverflowException(Number number, Class<?> targetClass) {
    throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
            + number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
}

From source file:com.github.jessemull.microflex.util.BigDecimalUtil.java

/**
 * Safely converts a number to a BigInteger. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    object to parse//w ww . j a v a  2 s  .c om
 * @return             parsed object
 * @throws   ArithmeticException    on overflow
 */
public static BigDecimal toBigDecimal(Number number) {

    /* Switch on class and convert to BigDecimal */

    String type = number.getClass().getSimpleName();
    BigDecimal parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = new BigDecimal(by.doubleValue());
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = new BigDecimal(sh.doubleValue());
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = new BigDecimal(in.doubleValue());
        break;

    case "Long":
        Long lo = (Long) number;
        parsed = new BigDecimal(lo.doubleValue());
        break;

    case "Float":
        Float fl = (Float) number;
        parsed = new BigDecimal(fl.doubleValue());
        break;

    case "BigInteger":
        parsed = new BigDecimal(((BigInteger) number));
        break;

    case "BigDecimal":
        parsed = (BigDecimal) number;
        break;

    case "Double":
        Double db = (Double) number;
        parsed = new BigDecimal(db);
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.github.jessemull.microflex.util.BigIntegerUtil.java

/**
 * Safely converts a number to a BigInteger. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    object to parse// w w  w  . j ava  2  s  .c  o m
 * @return             parsed object
 * @throws   ArithmeticException    on overflow
 */
public static BigInteger toBigInteger(Number number) {

    /* Switch on class and convert to BigInteger */

    String type = number.getClass().getSimpleName();
    BigInteger parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = new BigInteger(by.toString());
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = new BigInteger(sh.toString());
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = new BigInteger(in.toString());
        break;

    case "Long":
        Long lo = (Long) number;
        parsed = new BigInteger(lo.toString());
        break;

    case "Float":
        Float fl = (Float) number;
        parsed = new BigInteger(fl.toString());
        break;

    case "BigInteger":
        parsed = (BigInteger) number;
        break;

    case "BigDecimal":
        parsed = ((BigDecimal) number).toBigInteger();
        break;

    case "Double":
        Double db = (Double) number;
        parsed = new BigInteger(db.toString());
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.github.jessemull.microflex.util.IntegerUtil.java

/**
 * Safely converts a number to an integer. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    number to parse/* w  w w  .  j  a v a 2s.c  o  m*/
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static int toInteger(Number number) {

    /* Switch on class and convert to an int */

    String type = number.getClass().getSimpleName();
    int parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = by.intValue();
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = sh.intValue();
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = in.intValue();
        break;

    case "Long":
        Long lo = (Long) number;
        if (!OverFlowUtil.intOverflow(lo)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = lo.intValue();
        break;

    case "Float":
        Float fl = (Float) number;
        if (!OverFlowUtil.intOverflow(fl)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = fl.intValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) number;
        if (!OverFlowUtil.intOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bi.intValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) number;
        if (!OverFlowUtil.intOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bd.intValue();
        break;

    case "Double":
        Double db = (Double) number;
        if (!OverFlowUtil.intOverflow(db)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = db.intValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.github.jessemull.microflex.util.DoubleUtil.java

/**
 * Safely converts a number to a double. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    number to parse/* w  w w  .j  a va2  s  . c o m*/
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static double toDouble(Number number) {

    /* Switch on class and convert to double */

    String type = number.getClass().getSimpleName();
    double parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = by.doubleValue();
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = sh.doubleValue();
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = in.doubleValue();
        break;

    case "Long":
        Long lo = (Long) number;
        parsed = lo.doubleValue();
        break;

    case "Float":
        Float fl = (Float) number;
        parsed = fl.doubleValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) number;
        if (!OverFlowUtil.doubleOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + number + " to a double.");
        }
        parsed = bi.doubleValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) number;
        if (!OverFlowUtil.doubleOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + number + " to a double.");
        }
        parsed = bd.doubleValue();
        break;

    case "Double":
        Double db = (Double) number;
        parsed = db.doubleValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.espertech.esper.epl.parse.ASTContextHelper.java

public static CreateContextDesc walkCreateContext(Tree parent, Map<Tree, ExprNode> astExprNodeMap,
        Map<Tree, EvalFactoryNode> astPatternNodeMap, PropertyEvalSpec propertyEvalSpec,
        FilterSpecRaw filterSpec) {/*from   w  w  w  .ja  v a2s  . c  o  m*/
    String contextName = parent.getChild(0).getText();
    Tree detailParent = parent.getChild(1);

    ContextDetail contextDetail;

    // temporal fixed (start+end) and overlapping (initiated/terminated)
    if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_INIT
            || detailParent.getType() == EsperEPL2Ast.CREATE_CTX_FIXED) {
        ContextDetailCondition startEndpoint;
        if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_FIXED) {
            if (detailParent.getChild(0).getType() == EsperEPL2Ast.IDENT) {
                String ident = detailParent.getChild(0).getText().toLowerCase();
                if (!ident.equals("now")) {
                    throw new ASTWalkException(
                            "Expected 'now' keyword after '@', found '" + ident + "' instead");
                }
                startEndpoint = new ContextDetailConditionImmediate();
            } else {
                startEndpoint = getContextCondition(detailParent.getChild(0), astExprNodeMap, astPatternNodeMap,
                        propertyEvalSpec, false);
            }
        } else {
            boolean immediate = false;
            if (detailParent.getChild(detailParent.getChildCount() - 1).getType() == EsperEPL2Ast.IDENT) {
                String ident = detailParent.getChild(detailParent.getChildCount() - 1).getText().toLowerCase();
                if (!ident.equals("now")) {
                    throw new ASTWalkException(
                            "Expected 'now' keyword after '@', found '" + ident + "' instead");
                }
                immediate = true;
            }
            startEndpoint = getContextCondition(detailParent.getChild(0), astExprNodeMap, astPatternNodeMap,
                    propertyEvalSpec, immediate);
        }
        ContextDetailCondition endEndpoint = getContextCondition(detailParent.getChild(1), astExprNodeMap,
                astPatternNodeMap, propertyEvalSpec, false);
        boolean overlapping = detailParent.getType() == EsperEPL2Ast.CREATE_CTX_INIT;
        contextDetail = new ContextDetailInitiatedTerminated(startEndpoint, endEndpoint, overlapping);
    }
    // categorized
    else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_CAT) {
        List<ContextDetailCategoryItem> items = new ArrayList<ContextDetailCategoryItem>();
        for (int i = 0; i < detailParent.getChildCount() - 1; i++) {
            Tree categoryParent = detailParent.getChild(i);
            ExprNode exprNode = astExprNodeMap.remove(categoryParent.getChild(0));
            String name = categoryParent.getChild(1).getText();
            items.add(new ContextDetailCategoryItem(exprNode, name));
        }
        filterSpec = ASTExprHelper.walkFilterSpec(detailParent.getChild(detailParent.getChildCount() - 1),
                propertyEvalSpec, astExprNodeMap);
        contextDetail = new ContextDetailCategory(items, filterSpec);
    }
    // partitioned
    else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_PART) {
        List<ContextDetailPartitionItem> rawSpecs = new ArrayList<ContextDetailPartitionItem>();
        for (int i = 0; i < detailParent.getChildCount(); i++) {

            Tree partitionParent = detailParent.getChild(i);
            filterSpec = ASTExprHelper.walkFilterSpec(partitionParent.getChild(0), propertyEvalSpec,
                    astExprNodeMap);
            propertyEvalSpec = null;

            List<String> propertyNames = new ArrayList<String>();
            for (int j = 1; j < partitionParent.getChildCount(); j++) {
                String propertyName = ASTFilterSpecHelper.getPropertyName(partitionParent.getChild(j), 0);
                propertyNames.add(propertyName);
            }

            rawSpecs.add(new ContextDetailPartitionItem(filterSpec, propertyNames));
        }
        contextDetail = new ContextDetailPartitioned(rawSpecs);
    }
    // partitioned
    else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_COAL) {
        List<ContextDetailHashItem> rawSpecs = new ArrayList<ContextDetailHashItem>();
        int count = 0;
        for (int i = 0; i < detailParent.getChildCount(); i++) {
            Tree hashItemParent = detailParent.getChild(i);
            if (hashItemParent.getType() == EsperEPL2Ast.COALESCE) {
                count++;
                ExprChainedSpec func = ASTLibHelper.getLibFunctionChainSpec(hashItemParent.getChild(0),
                        astExprNodeMap);
                filterSpec = ASTExprHelper.walkFilterSpec(hashItemParent.getChild(1), propertyEvalSpec,
                        astExprNodeMap);
                propertyEvalSpec = null;
                rawSpecs.add(new ContextDetailHashItem(func, filterSpec));
            }
        }

        String granularity = detailParent.getChild(count).getText();
        if (!granularity.toLowerCase().equals("granularity")) {
            throw new ASTWalkException("Expected 'granularity' keyword after list of coalesce items, found '"
                    + granularity + "' instead");
        }
        Number num = (Number) ASTConstantHelper.parse(detailParent.getChild(count + 1));
        String preallocateStr = detailParent.getChildCount() - 1 < count + 2 ? null
                : detailParent.getChild(count + 2).getText();
        if (preallocateStr != null && !preallocateStr.toLowerCase().equals("preallocate")) {
            throw new ASTWalkException("Expected 'preallocate' keyword after list of coalesce items, found '"
                    + preallocateStr + "' instead");
        }
        if (!JavaClassHelper.isNumericNonFP(num.getClass())
                || JavaClassHelper.getBoxedType(num.getClass()) == Long.class) {
            throw new ASTWalkException(
                    "Granularity provided must be an int-type number, received " + num.getClass() + " instead");
        }

        contextDetail = new ContextDetailHash(rawSpecs, num.intValue(), preallocateStr != null);
    } else if (detailParent.getType() == EsperEPL2Ast.CREATE_CTX_NESTED) {
        List<CreateContextDesc> contexts = new ArrayList<CreateContextDesc>();
        for (int i = 0; i < detailParent.getChildCount(); i++) {
            Tree parentCreate = detailParent.getChild(i);
            if (parentCreate.getType() != EsperEPL2Ast.CREATE_CTX) {
                throw new IllegalStateException(
                        "Child to nested context is not a context-create but type " + parentCreate.getType());
            }
            contexts.add(walkCreateContext(parentCreate, astExprNodeMap, astPatternNodeMap, propertyEvalSpec,
                    filterSpec));
        }
        contextDetail = new ContextDetailNested(contexts);
    } else {
        throw new IllegalStateException("Unrecognized context detail type '" + detailParent.getType() + "'");
    }

    return new CreateContextDesc(contextName, contextDetail);
}

From source file:com.jkoolcloud.tnt4j.streams.utils.NumericFormatter.java

/**
 * Formats the specified object using the defined pattern, or using the default numeric formatting if no pattern was
 * defined.//w  ww  .  j  a v  a 2  s .  c o  m
 *
 * @param formatter
 *            formatter object to apply to value
 * @param radix
 *            the radix to use while parsing numeric strings
 * @param value
 *            value to convert
 * @param scale
 *            value to multiply the formatted value by
 *
 * @return formatted value of field in required internal data type
 *
 * @throws ParseException
 *             if an error parsing the specified value based on the field definition (e.g. does not match defined
 *             pattern, etc.)
 */
private static Number parse(DecimalFormat formatter, int radix, Object value, Number scale)
        throws ParseException {
    if (value == null) {
        return null;
    }
    if (scale == null) {
        scale = 1.0;
    }
    try {
        Number numValue = null;
        if (formatter == null && value instanceof String) {
            String strValue = (String) value;
            if (strValue.startsWith("0x") || strValue.startsWith("0X")) { // NON-NLS
                numValue = Long.parseLong(strValue.substring(2), 16);
            }
        }
        if (numValue == null) {
            if (formatter != null) {
                numValue = formatter.parse(value.toString());
            } else if (radix != 10) {
                numValue = Long.parseLong(value.toString(), radix);
            } else {
                numValue = value instanceof Number ? (Number) value : Double.valueOf(value.toString());
            }
        }
        Number scaledValue = numValue.doubleValue() * scale.doubleValue();
        return Utils.castNumber(scaledValue, numValue.getClass());
    } catch (NumberFormatException nfe) {
        throw new ParseException(nfe.getLocalizedMessage(), 0);
    }
}

From source file:net.dontdrinkandroot.persistence.dao.NumericEntityDaoTest.java

@Test
@Transactional//from w ww .java  2 s  .c  o m
public void testQuot() {
    NumericEntity entity2 = new NumericEntity();
    entity2.setLongField(2L);
    entity2.setIntField(3);
    entity2 = this.save(entity2);

    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<Number> criteriaQuery = builder.createQuery(Number.class);
    final Root<NumericEntity> root = criteriaQuery.from(NumericEntity.class);
    final Expression<Number> quot = builder.quot(
            builder.prod(builder.literal(1f), root.get(NumericEntity_.intField)),
            root.get(NumericEntity_.longField));
    criteriaQuery.select(quot);

    final Number result = this.findSingle(criteriaQuery);
    Assert.assertEquals(Float.class, result.getClass());
    Assert.assertEquals(3 / 2f, result);
}