Example usage for java.lang Class getDeclaredConstructor

List of usage examples for java.lang Class getDeclaredConstructor

Introduction

In this page you can find the example usage for java.lang Class getDeclaredConstructor.

Prototype

@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

Usage

From source file:org.argouml.moduleloader.ModuleLoader2.java

/**
 * Try to load a module from the given ClassLoader.
 * <p>/*  w ww.  j  ava2 s .  c o  m*/
 *
 * Only add it as a module if it is a module (i.e. it implements the
 * {@link ModuleInterface} interface.
 *
 * @param classLoader
 *            The ClassLoader to load from.
 * @param classname
 *            The name.
 * @throws ClassNotFoundException
 *             if the class classname is not found.
 */
private boolean addClass(ClassLoader classLoader, String classname) throws ClassNotFoundException {

    LOG.log(Level.INFO, "Loading module " + classname);
    Class moduleClass;
    try {
        moduleClass = classLoader.loadClass(classname);
    } catch (UnsupportedClassVersionError e) {
        LOG.log(Level.SEVERE, "Unsupported Java class version for " + classname);
        return false;
    } catch (NoClassDefFoundError e) {
        LOG.log(Level.SEVERE, "Unable to find required class while loading " + classname
                + " - may indicate an obsolete" + " extension module or an unresolved dependency", e);
        return false;
    } catch (Throwable e) {
        if (e instanceof ClassNotFoundException) {
            throw (ClassNotFoundException) e;
        }
        LOG.log(Level.SEVERE, "Unexpected error while loading " + classname, e);
        return false;
    }

    if (!ModuleInterface.class.isAssignableFrom(moduleClass)) {
        LOG.log(Level.FINE, "The class {0} is not a module.", classname);
        return false;
    }

    Constructor defaultConstructor;
    try {
        defaultConstructor = moduleClass.getDeclaredConstructor(new Class[] {});
    } catch (SecurityException e) {
        LOG.log(Level.SEVERE, "The default constructor for class " + classname + " is not accessable.", e);
        return false;
    } catch (NoSuchMethodException e) {
        LOG.log(Level.SEVERE, "The default constructor for class " + classname + " is not found.", e);
        return false;
    } catch (NoClassDefFoundError e) {
        LOG.log(Level.SEVERE, "Unable to find required class while loading " + classname
                + " - may indicate an obsolete" + " extension module or an unresolved dependency", e);
        return false;
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, "Unexpected error while loading " + classname, e);
        return false;
    }

    if (!Modifier.isPublic(defaultConstructor.getModifiers())) {
        LOG.log(Level.SEVERE,
                "The default constructor for class " + classname + " is not public.  Not loaded.");
        return false;
    }
    Object moduleInstance;
    try {
        moduleInstance = defaultConstructor.newInstance(new Object[] {});
    } catch (IllegalArgumentException e) {
        LOG.log(Level.SEVERE, "The constructor for class " + classname + " is called with incorrect argument.",
                e);
        return false;
    } catch (InstantiationException e) {
        LOG.log(Level.SEVERE, "The constructor for class " + classname + " threw an exception.", e);
        return false;
    } catch (IllegalAccessException e) {
        LOG.log(Level.SEVERE, "The constructor for class " + classname + " is not accessible.", e);
        return false;
    } catch (InvocationTargetException e) {
        LOG.log(Level.SEVERE, "The constructor for class " + classname + " cannot be called.", e);
        return false;
    } catch (NoClassDefFoundError e) {
        LOG.log(Level.SEVERE, "Unable to find required class while instantiating " + classname
                + " - may indicate an obsolete" + " extension module or an unresolved dependency", e);
        return false;
    } catch (Throwable e) {
        LOG.log(Level.SEVERE, "Unexpected error while instantiating " + classname, e);
        return false;
    }

    // The following check should have been satisfied before we
    // instantiated the module, but double check again
    if (!(moduleInstance instanceof ModuleInterface)) {
        LOG.log(Level.SEVERE, "The class " + classname + " is not a module.");
        return false;
    }
    ModuleInterface mf = (ModuleInterface) moduleInstance;

    addModule(mf);
    LOG.log(Level.INFO, "Succesfully loaded module {0}", classname);
    return true;
}

From source file:com.adf.bean.AbsBean.java

/**
 * IMPORT//  w  w  w.  ja va2s.c  om
 * */
public void setValueByColumn(String col, String val) throws IllegalArgumentException {
    try {
        Field f = getClass().getDeclaredField(col);
        Class<?> cls = f.getType();
        f.setAccessible(true);
        if (cls.isArray()) {
            JSONArray arr;
            try {
                arr = new JSONArray(val);
                setArrayColumn(col, arr);
            } catch (JSONException e) {
            }
            return;
        }
        if ((int.class == cls) || (Integer.class == cls)) {
            int ival = Integer.parseInt(val);
            f.set(this, ival);
        } else if ((long.class == cls) || (Long.class == cls)) {
            long lval = Long.parseLong(val);
            f.set(this, lval);
        } else if ((float.class == cls) || (Float.class == cls)) {
            float fval = Float.parseFloat(val);
            f.set(this, fval);
        } else if ((short.class == cls) || (Short.class == cls)) {
            short sval = Short.parseShort(val);
            f.set(this, sval);
        } else if ((double.class == cls) || (Double.class == cls)) {
            double dval = Double.parseDouble(val);
            f.set(this, dval);
        } else if ((byte.class == cls) || (Byte.class == cls)) {
            byte bval = Byte.parseByte(val);
            f.set(this, bval);
        } else if ((boolean.class == cls) || (Boolean.class == cls)) {
            boolean bval = Boolean.parseBoolean(val);
            f.set(this, bval);
        } else if (char.class == cls) {
            char cval = val.charAt(0);
            f.set(this, cval);
        } else {
            Constructor<?> cons = cls.getDeclaredConstructor(String.class);
            cons.setAccessible(true);
            Object obj = cons.newInstance(val);
            f.set(this, obj);
        }
    } catch (NoSuchFieldException e) {
        LogUtil.err("setValueByColumn NoSuchFieldException, col " + col + " not exist!!!");
    } catch (IllegalAccessException e) {
        LogUtil.err("setValueByColumn IllegalAccessException, col " + col + " :" + e.getMessage());
        //throw e;
    } catch (IllegalArgumentException e) {
        LogUtil.err("setValueByColumn IllegalArgumentException, col " + col + " :" + e.getMessage());
        //throw e;
    } catch (NoSuchMethodException e) {
        LogUtil.err("setValueByColumn NoSuchMethodException, col " + col + " :" + e.getMessage());
        //throw e;
    } catch (InstantiationException e) {
        LogUtil.err("setValueByColumn InstantiationException, col " + col + " :" + e.getMessage());
        //throw e;
    } catch (InvocationTargetException e) {
        LogUtil.err("setValueByColumn InvocationTargetException, col " + col + " :" + e.getMessage());
        //throw e;
    }
}

From source file:org.apache.ojb.broker.core.PersistenceBrokerImpl.java

/**
 * Creates a proxy instance./*from  ww w  .  j ava2  s.  c  om*/
 * 
 * @param baseClassForProxy  The base class that the Proxy should extend. For dynamic Proxies, the method of 
 *                           generation is dependent on the ProxyFactory implementation.
 * @param realSubjectsIdentity The identity of the subject
 * @return An instance of the proxy subclass
 * @throws PersistenceBrokerException If there is an error creating the proxy object
 */
public Object createProxy(Class baseClassForProxy, Identity realSubjectsIdentity) {
    try {
        // the invocation handler manages all delegation stuff
        IndirectionHandler handler = getProxyFactory().createIndirectionHandler(pbKey, realSubjectsIdentity);

        // the proxy simply provides the interface of the real subject
        if (VirtualProxy.class.isAssignableFrom(baseClassForProxy)) {
            Constructor constructor = baseClassForProxy
                    .getDeclaredConstructor(new Class[] { IndirectionHandler.class });
            return constructor.newInstance(new Object[] { handler });
        } else {
            return getProxyFactory().createProxy(baseClassForProxy, handler);
        }

    } catch (Exception ex) {
        throw new PersistenceBrokerException(
                "Unable to create proxy using class:" + baseClassForProxy.getName(), ex);
    }
}

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

/**
 * {@link jp.furplag.util.commons.NumberUtils#round(Object, Class)}.
 *///from ww w.j a v a2 s  .  c om
@SuppressWarnings("unchecked")
@Test
public void testRoundObjectClassOfT() {
    try {
        for (Class<?> type : NUMBERS) {
            Object expected = null;
            if (ClassUtils.isPrimitiveOrWrapper(type)) {
                expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null,
                        "3");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("3");
            }
            assertEquals("PI: " + type.getSimpleName(), expected,
                    round(Math.PI, (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.NumberObject}
 *///from   ww  w .jav a  2 s  .c  o  m
@SuppressWarnings("unchecked")
@Test
public void NumberObjectTest() {
    try {
        Class<?> numberObject = ClassLoader.getSystemClassLoader()
                .loadClass(NumberUtils.class.getName() + "$NumberObject");

        Constructor<?> c = numberObject.getDeclaredConstructor(Class.class);
        c.setAccessible(true);

        Method ofType = numberObject.getMethod("of", Class.class);
        ofType.setAccessible(true);

        Method ofN = numberObject.getMethod("of", Number.class);
        ofN.setAccessible(true);

        Method parsable = numberObject.getDeclaredMethod("parsable", Number.class);
        parsable.setAccessible(true);

        Method contains = numberObject.getDeclaredMethod("contains", Number.class);
        contains.setAccessible(true);

        Method valueOf = numberObject.getDeclaredMethod("valueOf", Number.class);
        valueOf.setAccessible(true);

        for (Class<?> type : NUMBERS) {
            Object o = c.newInstance(type);
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            Object numob = ofType.invoke(null, type);
            assertEquals("ofType: " + type.getSimpleName(), o, numob);
            Number n = null;
            if (!type.isPrimitive()) {
                if (ClassUtils.isPrimitiveWrapper(type)) {
                    n = (Number) ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                            .invoke(null, "1");
                } else {
                    n = (Number) type.getField("ONE").get(null);
                }
                if (type.equals(byte.class))
                    assertEquals("ofN: 1: " + type.getSimpleName(), o, ofN.invoke(null, n));
            }
            assertEquals("parsable: -1: " + type.getSimpleName(), true, parsable.invoke(numob, -1));
            assertEquals("parsable: 0: " + type.getSimpleName(), true, parsable.invoke(numob, 0));
            assertEquals("parsable: 1: " + type.getSimpleName(), true, parsable.invoke(numob, 1));

            assertEquals("parsable: null: " + type.getSimpleName(), !type.isPrimitive(),
                    parsable.invoke(numob, (Number) null));

            Object expected = ObjectUtils.isAny(wrapper, Float.class, Double.class, BigDecimal.class,
                    BigInteger.class);
            assertEquals("parsable: Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE));
            assertEquals("parsable: Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.toBigInteger()));
            assertEquals("parsable: Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT));
            assertEquals("parsable: Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.toBigInteger()));
            assertEquals("parsable: -Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate()));
            assertEquals("parsable: -Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate().toBigInteger()));
            assertEquals("parsable: -Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate()));
            assertEquals("parsable: -Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate().toBigInteger()));

            expected = ObjectUtils.isAny(wrapper, Float.class, Double.class);
            assertEquals("parsable: NaN: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NaN));
            assertEquals("parsable: NaN: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NaN));

            if (Byte.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 1234.56f));
            }
            if (Short.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 12345.6f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 123456.789f));
            }
            if (Integer.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123456.789f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456d));
            }
            if (Long.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456f));
            }
            if (Float.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, -Double.MAX_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Double.MAX_VALUE));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, -Double.MAX_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Double.MAX_VALUE));
            }
            if (Double.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));
            }
            if (!ClassUtils.isPrimitiveWrapper(wrapper)) {
                assertEquals("parsable: fraction: " + type.getSimpleName(), BigDecimal.class.equals(type),
                        parsable.invoke(numob, 123.456f));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
            }

            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                expected = new BigDecimal("123");
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    n = (Number) valueType.getMethod("valueOf", String.class).invoke(null, "123");
                } else {
                    n = new BigDecimal("123");
                    if (BigInteger.class.equals(valueType))
                        n = ((BigDecimal) n).toBigInteger();
                }
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        expected, valueOf.invoke(numob, n));
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: "
                                + type.getSimpleName(),
                        expected.getClass(), valueOf.invoke(numob, n).getClass());
            }

            n = 123.456f;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Float) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = 1.23456789E-6d;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Double) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2);
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: " + type.getSimpleName(), expected, valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2).negate();
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: negative: " + type.getSimpleName(), expected,
                    valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: negative: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());
        }
    } 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#add(java.lang.Object, java.lang.Number)}.
 *//*from w  ww  . j ava2  s . c o m*/
@SuppressWarnings("unchecked")
@Test
public void testAddObjectT() {
    assertEquals("null", null, add((Object) null, null));
    assertEquals("null", null, add("123.456", null));
    assertEquals("null", (Object) 10, add("", 10));
    assertEquals("null", (Object) 10, add((Object) null, 10));
    assertEquals("null", (Object) 123, add("123.456", 0));
    assertEquals("null", (Object) 123.456f, add("123.456d", 0f));
    assertEquals("123 + .456: Float", (Object) 123.456f, add("123", .456f));
    assertEquals("123 + .456: Float", (Object) Float.class, add("123d", .456f).getClass());
    assertEquals("123 + .456: Float", (Object) Float.class,
            add((Object) BigDecimal.valueOf(123d), .456f).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object o = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                o = c.newInstance("123");
            }
            assertEquals("123.456: " + type.getSimpleName(), add(".456", (Number) o, typeOfN),
                    add(".456", (Number) o));
        } 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#ceil(java.lang.Object, java.lang.Class)}.
 *//*from   w ww. j a v a2s  .c  o  m*/
@SuppressWarnings("unchecked")
@Test
public void testCeilObjectClassOfT() {
    assertEquals("null", null, ceil(null, null));
    assertEquals("null", null, ceil("", null));
    assertEquals("null", null, ceil("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, "4");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("4");
            }
            assertEquals("PI: String: " + type.getSimpleName(), expected, ceil("3.14", typeOfN));
            assertEquals("PI: Float: " + type.getSimpleName(), expected, ceil(3.141592653589793f, typeOfN));
            assertEquals("PI: Double: " + type.getSimpleName(), expected, ceil(Math.PI, typeOfN));
            assertEquals("PI: BigDecimal: " + type.getSimpleName(), expected,
                    ceil(BigDecimal.valueOf(Math.PI), typeOfN));
            assertEquals("(Double) (10 / 3): " + type.getSimpleName(), expected, ceil(
                    (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,
                        ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), typeOfN));
            } else if (BigDecimal.class.equals(type)) {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toPlainString();
                Object actual = ceil((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 = ceil((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:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#floor(java.lang.Object, java.lang.Class)}.
 *///w w w .  j a v  a  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:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Number, java.lang.Number)}.
 *///from   ww  w. j av  a  2s .  c  o m
@SuppressWarnings("unchecked")
@Test
public void testAddTNumber() {
    assertEquals("null", null, add(null, null));
    assertEquals("null", null, add(null, 10));
    assertEquals("null", (Object) 123.456d, add(123.456, 0));
    assertEquals("null", (Object) 123.456f, add(123.456f, 0));
    assertEquals("123 + .456: Float", (Object) 123, add(123, .456f));
    assertEquals("123 + .456: Float", (Object) Double.class, add(123d, .456f).getClass());
    assertEquals("123 + .456: Float", (Object) BigDecimal.class,
            add(BigDecimal.valueOf(123d), .456f).getClass());
    for (Class<?> type : NUMBERS) {
        try {
            Object o = null;
            Number augend = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                o = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                o = c.newInstance("123");
            }
            assertEquals("123.456: " + type.getSimpleName(), add((Number) o, augend, typeOfN),
                    add((Number) o, augend));
            augend = .456f;
            assertEquals("123.456: " + type.getSimpleName(), add((Number) o, augend, typeOfN),
                    add((Number) o, augend));
            augend = Double.NaN;
            assertEquals("NaN: " + type.getSimpleName(), add((Number) o, augend, typeOfN),
                    add((Number) o, augend));
            augend = Float.NEGATIVE_INFINITY;
            assertEquals("-Infinity: Float: " + type.getSimpleName(), add((Number) o, augend, typeOfN),
                    add((Number) o, augend));
            augend = Double.POSITIVE_INFINITY;
            assertEquals("Infinity: Double: : " + type.getSimpleName(), add((Number) o, augend, typeOfN),
                    add((Number) o, augend));

        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:com.oceans7.mobile.eagleswag.persistence.parsers.JsonDataFileParserStrategy.java

/**
 * This parsing method uses the convention over configuration paradigm,
 * where the name of the data file containing the questions data matches the
 * class name (simple class name) of the key provided, with a ".json" file
 * extension. For example, if GeneralQuestion.class is provided as the key,
 * the data file name expected is "GeneralQuestion.json." Likewise, the
 * object name for the array containing the questions data within the data
 * file is simple class name of the key provided. For example, if
 * GeneralQuestion.class is provided as a key, the format of the data file
 * would be://  www.  j ava 2  s  .c  o m
 * 
 * <pre>
 * {
 *   "GeneralQuestion": [
 *     {
 *       "text": "General question 1",
 *       "yesValue": "10",
 *       "noValue": "0",
 *       "usedCount": "0"
 *     },
 *           .
 *           .
 *           .
 *     ]
 * }
 * </pre>
 * 
 * If no data file is found for the key provided, an empty queue is
 * returned.
 * <p/>
 * 
 * {@inheritDoc}
 * 
 * @see com.oceans7.mobile.eagleswag.persistence.DataFileParserStrategy#getQuestion(java.lang.Class)
 */
@Override
public <T extends Question> Queue<T> getQuestions(Class<T> key) {

    // The queue used to store the questions retrieved from the data file
    Queue<T> questions = new LinkedList<T>();

    // Set the object name for the data file and the name of the data file
    // to the simple name of the key. This is the implementation of the
    // "convention over configuration" mechanism for obtaining data.
    String id = key.getSimpleName();
    String dataFileName = key.getSimpleName() + EXTENSION;

    try {

        // The JSON parser to parse the data file
        JSONParser parser = new JSONParser();

        // Open the JSON file containing the questions
        InputStream dataFileInputStream = this.context.getAssets().open(DATA_FILE_ASSET_PATH + dataFileName);

        // Parse the JSON file
        JSONObject jsonObj = (JSONObject) parser.parse(new InputStreamReader(dataFileInputStream));
        dataFileInputStream.close();

        // Obtain a JSON array for the question type supplied (dependent on
        // the ID supplied)
        JSONArray questionsArray = (JSONArray) jsonObj.get(id);

        for (Object question : questionsArray) {
            // Loop through each of the questions found in the data file

            // Convert the object to a JSON object
            JSONObject jsonQuestion = (JSONObject) question;

            // --------------------------------------------------------------
            // Extract the JSON values (note that the ID value is set to 0
            // because it will be supplied later by the data controller
            // (there is no ID associated with the questions in the
            // questions data file)
            // --------------------------------------------------------------
            int questionId = 0;
            String text = (String) jsonQuestion.get(QUESTION_TEXT_ID);
            int yesValue = Integer.parseInt((String) jsonQuestion.get(YES_VALUE_ID));
            int noValue = Integer.parseInt((String) jsonQuestion.get(NO_VALUE_ID));
            int usedCount = Integer.parseInt((String) jsonQuestion.get(USED_COUNT_ID));

            // Obtain the constructor for the supplied class
            Class<?>[] argTypes = new Class<?>[] { Integer.class, String.class, Integer.class, Integer.class,
                    Integer.class };
            Constructor<T> constructor = key.getDeclaredConstructor(argTypes);
            Object[] args = new Object[] { questionId, text, yesValue, noValue, usedCount };

            // Invoke the constructor to obtain the object
            T questionToAdd = constructor.newInstance(args);

            // Add the new general question (ignoring the ID)
            questions.add(questionToAdd);
        }
    } catch (FileNotFoundException e) {
        // A data file for the key provided cannot be found
        Log.e(this.getClass().getName(),
                "No data file named '" + dataFileName + "' found in '" + DATA_FILE_ASSET_PATH + "'");
    } catch (IOException e) {
        // IO exception occurred while accessing the JSON data file
        Log.e(this.getClass().getName(), "IO exception occurred while parsing " + dataFileName + ": " + e);
    } catch (ParseException e) {
        // A parse exception occurred while parsing a data file
        Log.e(this.getClass().getName(),
                "A parser exception occurred while parsing " + dataFileName + ": " + e);
    } catch (NoSuchMethodException e) {
        // A constructor with the specified format cannot be found for key
        Log.e(this.getClass().getName(), "Could not find the desired constructor for the " + id + ": " + e);
    } catch (IllegalArgumentException e) {
        // The arguments for the question constructor are incorrect
        Log.e(this.getClass().getName(),
                "Invalid constructor arguments while trying to create new " + id + ": " + e);
    } catch (InstantiationException e) {
        // The selected question object could not be instantiated
        Log.e(this.getClass().getName(), "Could not not instantiate an object for " + id + ": " + e);
    } catch (IllegalAccessException e) {
        // The selected question constructor could not be accessed
        Log.e(this.getClass().getName(), "Could not access the desired constructor for " + id + ": " + e);
    } catch (InvocationTargetException e) {
        // The constructor could not be invoked on the target object
        Log.e(this.getClass().getName(), "Could not invoke constructor on the target " + id + ": " + e);
    }

    // Return the queue containing the questions (which may be empty)
    return questions;
}