Example usage for org.apache.commons.lang3 ClassUtils primitiveToWrapper

List of usage examples for org.apache.commons.lang3 ClassUtils primitiveToWrapper

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ClassUtils primitiveToWrapper.

Prototype

public static Class<?> primitiveToWrapper(final Class<?> cls) 

Source Link

Document

Converts the specified primitive Class object to its corresponding wrapper Class object.

NOTE: From v2.2, this method handles Void.TYPE , returning Void.TYPE .

Usage

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the getter method from the declaring class suitable to get a
 * reference to the field.//  w  w w  .  j  a  v a  2 s  . c o  m
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @param  prefix the non-<code>null</code> getter prefix to use
 * @return the getter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable getter
 */
private Method findGetterMethod(Class<?> declaringClass, String prefix) {
    final String mname = prefix + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wrtype = ClassUtils.primitiveToWrapper(
                DataTypeImpl.unwrapOptionalIfPresent(m.getReturnType(), m.getGenericReturnType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wrtype),
                "expecting getter for field '%s' with return type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#contains(java.lang.Object, java.lang.Number, java.lang.Number)}.
 *//*from   ww  w. ja v a  2 s  . c  o  m*/
@SuppressWarnings("unchecked")
@Test
public void testContains() {
    assertEquals("null", false, contains(null, null, null));
    assertEquals("null", false, contains(null, 0, null));
    assertEquals("null", false, contains(null, null, 10));
    assertEquals("null", false, contains(null, 0, 10));
    assertEquals("null: from", true, contains(0, null, 10));
    assertEquals("null: from: overflow", false, contains(11, null, 10));
    assertEquals("null: to", true, contains(0, 0, null));
    assertEquals("null: to", true, contains(11, 10, null));
    assertEquals("null: to: less", false, contains(1, 10, null));
    assertEquals("fraction: Double", true, contains(Math.PI, 0, 10));
    assertEquals("fraction: Float", true, contains(Float.MIN_VALUE, 0, 10));
    assertEquals("NaN", false, contains(Float.NaN, -Float.MAX_VALUE, Float.MAX_VALUE));
    assertEquals("NaN", false, contains(Float.NaN, null, Float.POSITIVE_INFINITY));
    assertEquals("NaN", true, contains(Float.NaN, Float.NaN, Float.POSITIVE_INFINITY));
    assertEquals("NaN", true, contains(Float.NaN, null, Float.NaN));
    assertEquals("NaN", true, contains(Float.NaN, Double.NaN, Float.NaN));
    assertEquals("-Infinity: from", true, contains(1, Float.NEGATIVE_INFINITY, null));
    assertEquals("-Infinity: to", false, contains(1, null, Float.NEGATIVE_INFINITY));
    assertEquals("Infinity: from", false, contains(1, Float.POSITIVE_INFINITY, null));
    assertEquals("Infinity: to", true, contains(1, null, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", false, contains(1, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", true,
            contains(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("Infinity: only", true,
            contains(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    for (Class<?> type : NUMBERS) {
        Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
        Object o = null;
        try {
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getField("MAX_VALUE").get(null);
            } else {
                o = INFINITY_DOUBLE.pow(2);
                if (BigInteger.class.equals(type))
                    o = ((BigDecimal) o).toBigInteger();
            }
            assertEquals("Infinity: all: " + type.getSimpleName(), true,
                    contains(o, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY));
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the setter method from the declaring class suitable to set a
 * value for the field./*from   w  ww . java2  s.c  om*/
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @return the setter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable setter
 */
private Method findSetterMethod(Class<?> declaringClass) {
    final String mname = "set" + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname, type);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        org.apache.commons.lang3.Validate.isTrue(m.getParameterCount() == 1,
                "expecting setter for field '%s' with one parameter", field);
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wptype = ClassUtils.primitiveToWrapper(DataTypeImpl.unwrapOptionalIfPresent(
                m.getParameterTypes()[0], m.getParameters()[0].getParameterizedType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wptype),
                "expecting setter for field '%s' with parameter type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#divide(java.lang.Object, java.lang.Number, java.lang.Number, java.math.RoundingMode, java.lang.Class)}.
 *///from  ww w. j a va 2 s  . com
@SuppressWarnings("unchecked")
@Test
public void testDivideTNumberNumberRoundingModeClassOfT() {
    assertEquals("null", null, divide(null, null, null, null, null));
    assertEquals("null", null, divide(10, 5, 0, null, null));
    assertEquals("null", null, divide(10, 5, null, null, null));
    assertEquals("null", null, divide(10, 3, 2, RoundingMode.DOWN, null));
    assertEquals("null", (Object) 3.33f, divide(10, 3, 2, RoundingMode.DOWN, float.class));
    try {
        for (Class<?> type : PRIMITIVES) {
            Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                    .invoke(null, "0");
            assertEquals("fallback: " + type.getSimpleName(), expected,
                    divide(null, null, null, null, (Class<? extends Number>) type));
        }
        for (Class<?> type : NUMBERS) {
            Object expected = valueOf(3.33, (Class<? extends Number>) type);
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.DOWN, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.HALF_EVEN, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.FLOOR, (Class<? extends Number>) type));
            expected = valueOf(3.34, (Class<? extends Number>) type);
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.UP, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.CEILING, (Class<? extends Number>) type));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public Object compileProperty(Class<?> propertyType, String propertyName, Object propertyObjectValue) {
    Object compiled;//from  ww w.  j  a va 2  s .  co m
    try {
        compiled = Engine.theApp.databaseObjectsManager.getCompiledValue(propertyObjectValue);
        removeSymbolError(propertyName);
    } catch (UndefinedSymbolsException e) {
        addSymbolError(propertyName, e.undefinedSymbols());
        compiled = e.incompletValue();
    }

    if (compiled != propertyObjectValue) {
        setCompilablePropertySourceValue(propertyName, propertyObjectValue);
        propertyObjectValue = compiled;
    } else {
        removeCompilablePropertySourceValue(propertyName);
    }

    propertyType = ClassUtils.primitiveToWrapper(propertyType);
    if (Number.class.isAssignableFrom(propertyType)) {
        try {
            try {
                propertyObjectValue = propertyType.getConstructor(String.class)
                        .newInstance(propertyObjectValue.toString());
            } catch (Exception e) {
                Engine.logBeans.warn("(DatabaseObject) Failed to parse '" + propertyObjectValue + "' as "
                        + propertyType.getSimpleName() + ". Set 0 instead.");
                propertyObjectValue = propertyType.getConstructor(String.class).newInstance("0");
            }
        } catch (Exception e) {
            Engine.logBeans.error("(DatabaseObject) Failed to parse '" + propertyObjectValue + "' as "
                    + propertyType.getSimpleName());
        }
    } else if (Boolean.class.isAssignableFrom(propertyType)) {
        if (propertyObjectValue instanceof Integer) {
            propertyObjectValue = (Integer) propertyObjectValue == 0;
        } else {
            propertyObjectValue = Boolean.parseBoolean(propertyObjectValue.toString());
        }
    } else if (Enum.class.isAssignableFrom(propertyType) && propertyObjectValue instanceof String) {
        propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
    }
    return propertyObjectValue;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#floor(java.lang.Object, java.lang.Class)}.
 *///w w  w  . ja va 2  s . co m
@SuppressWarnings("unchecked")
@Test
public void testFloorObjectClassOfT() {
    assertEquals("null", null, floor(null, null));
    assertEquals("null", null, floor("", null));
    assertEquals("null", null, floor("not a number.", null));
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "3");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("3");
            }
            assertEquals("PI: String: " + type.getSimpleName(), expected, floor("3.14", typeOfN));
            assertEquals("PI: Float: " + type.getSimpleName(), expected, floor(3.141592653589793f, typeOfN));
            assertEquals("PI: Double: " + type.getSimpleName(), expected, floor(Math.PI, typeOfN));
            assertEquals("PI: BigDecimal: " + type.getSimpleName(), expected,
                    floor(BigDecimal.valueOf(Math.PI), typeOfN));
            assertEquals("(Double) (10 / 3): " + type.getSimpleName(), expected, floor(
                    (Object) (BigDecimal.TEN.divide(new BigDecimal("3"), MathContext.DECIMAL128)), typeOfN));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
                assertEquals("Huge: " + type.getSimpleName(), expected,
                        floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), typeOfN));
            } else if (BigDecimal.class.equals(type)) {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toPlainString();
                Object actual = floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigDecimal.class).toPlainString();
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            } else {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toBigInteger();
                Object actual = floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigInteger.class);
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:com.github.javalbert.reflection.ClassAccessFactory.java

private void visitGeneralAccessGetter(String methodName, String memberType,
        List<? extends AssignableInfo> memberInfoList) {
    mv = cw.visitMethod(ACC_PUBLIC, methodName, "(" + classTypeDescriptor + "I)Ljava/lang/Object;", null, null);
    mv.visitCode();/*from   w  w  w  .  ja  v a 2  s  .  c o  m*/
    Label firstLabel = new Label();
    mv.visitLabel(firstLabel);
    mv.visitVarInsn(ILOAD, 2);

    Label defaultCaseLabel = new Label();

    if (memberInfoList == null || memberInfoList.isEmpty()) {
        mv.visitInsn(POP);
        mv.visitLabel(defaultCaseLabel);
        visitAccessGetterLastPart(memberType, firstLabel);
        return;
    }

    Label[] labels = getTableSwitchLabelsForAccess(defaultCaseLabel, memberInfoList);

    // Always use a table switch because there are no gaps between member indices
    mv.visitTableSwitchInsn(memberInfoList.get(0).memberIndex,
            memberInfoList.get(memberInfoList.size() - 1).memberIndex, defaultCaseLabel, labels);

    for (int i = 0; i < memberInfoList.size(); i++) {
        AssignableInfo member = memberInfoList.get(i);

        mv.visitLabel(labels[i]);
        mv.visitFrame(F_SAME, 0, null, 0, null);
        mv.visitVarInsn(ALOAD, 1);

        switch (memberType) {
        case MEMBER_TYPE_FIELD:
            mv.visitFieldInsn(((FieldInfo) member).getFieldOpcode, internalName, member.name,
                    member.descriptor);
            break;
        case MEMBER_TYPE_PROPERTY:
            mv.visitMethodInsn(INVOKEVIRTUAL, internalName, ((PropertyInfo) member).readMethodName,
                    "()" + member.descriptor, false);
            break;
        }

        if (member.type.isPrimitive()) {
            Class<?> wrapperType = ClassUtils.primitiveToWrapper(member.type);
            mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(wrapperType), "valueOf",
                    "(" + member.descriptor + ")" + Type.getDescriptor(wrapperType), false);
        }

        mv.visitInsn(ARETURN);
    }

    mv.visitLabel(defaultCaseLabel);
    mv.visitFrame(F_SAME, 0, null, 0, null);

    visitAccessGetterLastPart(memberType, firstLabel);
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#floor(java.lang.Object, java.lang.Number, java.lang.Class)}.
 *//*from w  w w  . jav  a  2s . co m*/
@SuppressWarnings("unchecked")
@Test
public void testFloorObjectNumberClassOfT() {
    assertEquals("null", null, floor(null, null, null));
    assertEquals("null", null, floor(null, 2, null));
    assertEquals("null", 3f, floor(3.14f, 0, null));
    assertEquals("null", 3.14d, floor(Math.PI, 2, null));
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (Double.class.equals(wrapper)) {
                expected = 3.14d;
            } else if (Float.class.equals(wrapper)) {
                expected = 3.14f;
            } else if (BigDecimal.class.equals(wrapper)) {
                expected = new BigDecimal("3.14");
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "3");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("3");
            }
            for (Class<?> scaleType : OBJECTS) {
                Object o = null;
                if (ClassUtils.isPrimitiveWrapper(scaleType)) {
                    o = scaleType.getMethod("valueOf", String.class).invoke(null, "2");
                } else {
                    Constructor<?> c = scaleType.getDeclaredConstructor(String.class);
                    o = c.newInstance("2");
                }
                assertEquals(
                        "PI: Float: " + type.getSimpleName() + "(scale: " + scaleType.getSimpleName() + ")",
                        expected, floor(3.141592653589793f, (Number) o, typeOfN));
                assertEquals(
                        "PI: Double: " + type.getSimpleName() + "(scale: " + scaleType.getSimpleName() + ")",
                        expected, floor(Math.PI, (Number) o, typeOfN));
                assertEquals("PI: BigDecimal: " + type.getSimpleName() + "(scale: " + scaleType.getSimpleName()
                        + ")", expected, floor(new BigDecimal(Math.PI), (Number) o, typeOfN));
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#multiply(java.lang.Object, java.lang.Number, java.lang.Class)}.
 *//*  w ww . j  a v a  2s  .  co m*/
@SuppressWarnings("unchecked")
@Test
public void testMultiplyObjectNumberClassOfT() {
    assertEquals("null", null, multiply(null, null, null));
    assertEquals("null", null, multiply(1, 23, null));
    assertEquals("null", null, multiply(1, 2, null));
    try {
        for (Class<?> type : PRIMITIVES) {
            Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                    .invoke(null, "0");
            assertEquals("fallback: " + type.getSimpleName(), expected,
                    multiply(null, null, (Class<? extends Number>) type));
        }
        for (Class<?> type : NUMBERS) {
            Object expected = valueOf(new BigDecimal("12").multiply(new BigDecimal("3.456")),
                    (Class<? extends Number>) type);
            assertEquals("12 * 3.456:" + type.getSimpleName(), expected,
                    multiply(12, 3.456, (Class<? extends Number>) type));
            if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = valueOf(valueOf("-Infinity"), (Class<? extends Number>) type);
            } else {
                expected = INFINITY_DOUBLE.pow(2).negate();
                if (BigInteger.class.equals(type))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("Infinity * -Infinity: " + type.getSimpleName(), expected,
                    multiply("Infinity", Double.NEGATIVE_INFINITY, (Class<? extends Number>) type));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#remainder(java.lang.Object, java.lang.Number, java.lang.Class)}.
 *//*w  ww  .  j ava 2s  .  co  m*/
@SuppressWarnings("unchecked")
@Test
public void testRemainderObjectNumberClassOfT() {
    assertEquals("null", null, remainder(null, null, null));
    assertEquals("null", null, remainder(10, 3, null));
    assertEquals("10 / 3", (Object) 1, remainder(10, 3, int.class));
    assertEquals("10 / 3", (Object) 1, remainder(10d, 3, int.class));
    assertEquals("10 / 3", (Object) 1f, remainder(10d, 3, float.class));
    try {
        for (Class<?> type : NUMBERS) {
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Object expected = null;
            if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null,
                        "1");
            } else {
                expected = type.getField("ONE").get(null);
            }
            for (Class<?> valueType : NUMBERS) {
                Object o = null;
                if (ClassUtils.isPrimitiveOrWrapper(valueType)) {
                    o = ClassUtils.primitiveToWrapper(valueType).getMethod("valueOf", String.class).invoke(null,
                            "10");
                } else {
                    o = valueType.getField("TEN").get(null);
                }
                assertEquals(o + "(" + o.getClass() + ") / 3: " + type.getSimpleName(), expected,
                        remainder(o, 3, typeOfN));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}