Example usage for java.lang.reflect Constructor setAccessible

List of usage examples for java.lang.reflect Constructor setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Constructor setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Document

A SecurityException is also thrown if this object is a Constructor object for the class Class and flag is true.

Usage

From source file:org.apache.hadoop.hbase.client.ConnectionManager.java

@Deprecated
static ClusterConnection createConnection(final Configuration conf, final boolean managed,
        final ExecutorService pool, final User user) throws IOException {
    String className = conf.get(HConnection.HBASE_CLIENT_CONNECTION_IMPL,
            HConnectionImplementation.class.getName());
    Class<?> clazz = null;//ww w.  j a  va  2 s.c  o  m
    try {
        clazz = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new IOException(e);
    }
    try {
        // Default HCM#HCI is not accessible; make it so before invoking.
        Constructor<?> constructor = clazz.getDeclaredConstructor(Configuration.class, boolean.class,
                ExecutorService.class, User.class);
        constructor.setAccessible(true);
        return (ClusterConnection) constructor.newInstance(conf, managed, pool, user);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:dinistiq.Dinistiq.java

/**
 * Creates an instance of the given type and registeres it with the container.
 *
 * @param dependencies dependencies within the scope
 * @param cls type to create an instance of
 * @param beanName beans name in the scope using the given dependencies
 *///from w  ww .  j a  va2s.c  om
private <T extends Object> T createInstance(Map<String, Set<Object>> dependencies, Class<T> cls,
        String beanName) throws Exception {
    LOG.info("createInstance({})", cls.getSimpleName());
    Constructor<?> c = null;
    Constructor<?>[] constructors = cls.getDeclaredConstructors();
    LOG.debug("createInstance({}) constructors.length={}", cls.getSimpleName(), constructors.length);
    for (Constructor<?> ctor : constructors) {
        LOG.debug("createInstance({}) {}", cls.getSimpleName(), ctor);
        c = (ctor.getAnnotation(Inject.class) != null) ? ctor : c;
    } // for
    c = (c == null) ? cls.getConstructor() : c;
    // Don't record constructor dependencies - they MUST be already fulfilled
    Object[] parameters = getParameters(null, null, beanName, c.getParameterTypes(),
            c.getGenericParameterTypes(), c.getParameterAnnotations());
    dependencies.put(beanName, new HashSet<>());
    boolean accessible = c.isAccessible();
    try {
        c.setAccessible(true);
        return convert(c.newInstance(parameters));
    } finally {
        c.setAccessible(accessible);
    } // try/finally
}

From source file:org.grouplens.grapht.reflect.internal.ClassInstantiator.java

@Override
public Object instantiate() throws ConstructionException {
    // find constructor and build up necessary constructor arguments

    Constructor<?> ctor = getConstructor();
    LogContext globalLogContext = LogContext.create();
    Object instance = null;//from w  w w  .j a  va  2  s  .  c o  m
    Method[] methods;

    try {
        // create the instance that we are injecting
        try {
            globalLogContext.put("org.grouplens.grapht.class", ctor.getClass().toString());
            Object[] ctorArgs = new Object[ctor.getParameterTypes().length];
            for (Desire d : desires) {
                LogContext ipContext = LogContext.create();
                if (d.getInjectionPoint() instanceof ConstructorParameterInjectionPoint) {
                    // this desire is a constructor argument so create it now
                    Instantiator provider = providers.get(d);
                    ConstructorParameterInjectionPoint cd = (ConstructorParameterInjectionPoint) d
                            .getInjectionPoint();
                    logger.trace("Injection point satisfactions in progress {}", cd);
                    try {
                        ipContext.put("org.grouplens.grapht.injectionPoint", cd.toString());
                    } finally {
                        ipContext.finish();
                    }
                    ctorArgs[cd.getParameterIndex()] = checkNull(cd, provider.instantiate());
                }
            }
            logger.trace("Invoking constructor {} with arguments {}", ctor, ctorArgs);
            ctor.setAccessible(true);
            instance = ctor.newInstance(ctorArgs);
        } catch (InvocationTargetException e) {
            throw new ConstructionException(ctor, "Constructor " + ctor + " failed", e);
        } catch (InstantiationException e) {
            throw new ConstructionException(ctor, "Could not instantiate " + type, e);
        } catch (IllegalAccessException e) {
            throw new ConstructionException(ctor, "Access violation on " + ctor, e);
        }

        // satisfy dependencies in the order of the list, which was
        // prepared to comply with JSR 330
        Map<Method, InjectionArgs> settersAndArguments = new HashMap<Method, InjectionArgs>();
        for (Desire d : desires) {
            LogContext ipContext = LogContext.create();
            try {
                final InjectionStrategy injectionStrategy = InjectionStrategy
                        .forInjectionPoint(d.getInjectionPoint());
                ipContext.put("org.grouplens.grapht.injectionPoint", d.getInjectionPoint().toString());
                injectionStrategy.inject(d.getInjectionPoint(), instance, providers.get(d),
                        settersAndArguments);
            } finally {
                ipContext.finish();
            }
        }
    } finally {
        globalLogContext.finish();
    }
    if (manager != null) {
        manager.registerComponent(instance);
    }

    methods = MethodUtils.getMethodsWithAnnotation(type, PostConstruct.class);
    for (Method method : methods) {
        method.setAccessible(true);
        try {
            method.invoke(instance);
        } catch (InvocationTargetException e) {
            throw new ConstructionException("Exception throw by " + method, e);
        } catch (IllegalAccessException e) {
            throw new ConstructionException("Access violation invoking " + method, e);
        }
    }

    // the instance has been fully configured
    return instance;
}

From source file:com.gs.collections.impl.test.Verify.java

private static <T> boolean canInstantiateThroughReflection(Class<T> aClass) {
    try {//ww w .  j a  v a 2  s  .c  o m
        Constructor<T> declaredConstructor = aClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        declaredConstructor.newInstance();
        return true;
    } catch (NoSuchMethodException e) {
        return false;
    } catch (InvocationTargetException e) {
        return false;
    } catch (InstantiationException e) {
        return false;
    } catch (IllegalAccessException e) {
        return false;
    } catch (AssertionError e) {
        return false;
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

/**
 * Returns a {@link Constructor} object that reflects the specified constructor of the given type.
 * <p/>//from ww w  .j a  v a2  s  . c  o m
 * If no parameter types are specified i.e., {@code paramTypes} is {@code null} or empty, the default constructor
 * is returned.<br/>
 * If a parameter type is not known i.e., it is {@code null}, all declared constructors are checked whether their
 * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter
 * type of the constructor and if exactly one was found, it is returned.<br/>
 * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several constructors were found.
 *
 * @param type the class
 * @param paramTypes the full-qualified class names of the parameters (can be {@code null})
 * @param classLoader the class loader to use
 * @return the accessible constructor resolved
 * @throws NoSuchMethodException if there are zero or more than one constructor candidates
 * @throws ClassNotFoundException if a class cannot be located by the specified class loader
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... clazzes)
        throws NoSuchMethodException, ClassNotFoundException {
    Constructor<T> constructor = null;

    // If all parameter types are known, find the constructor that exactly matches the signature
    if (!ArrayUtils.contains(clazzes, null)) {
        try {
            constructor = type.getDeclaredConstructor(clazzes);
        } catch (NoSuchMethodException e) {
            // Ignore
        }
    }

    // If no constructor was found, find all possible candidates
    if (constructor == null) {
        List<Constructor<T>> candidates = new ArrayList<>(1);
        for (Constructor<T> declaredConstructor : (Constructor<T>[]) type.getDeclaredConstructors()) {
            if (ClassUtils.isAssignable(clazzes, declaredConstructor.getParameterTypes())) {

                // Check if there is already a constructor method with the same signature
                for (int i = 0; i < candidates.size(); i++) {
                    Constructor<T> candidate = candidates.get(i);
                    /**
                     * If all parameter types of constructor A are assignable to the types of constructor B
                     * (at least one type is a subtype of the corresponding parameter), keep the one whose types
                     * are more concrete and drop the other one.
                     */
                    if (ClassUtils.isAssignable(declaredConstructor.getParameterTypes(),
                            candidate.getParameterTypes())) {
                        candidates.remove(candidate);
                        i--;
                    } else if (ClassUtils.isAssignable(candidate.getParameterTypes(),
                            declaredConstructor.getParameterTypes())) {
                        declaredConstructor = null;
                        break;
                    }
                }

                if (declaredConstructor != null) {
                    candidates.add(declaredConstructor);
                }
            }
        }
        if (candidates.size() != 1) {
            throw new NoSuchMethodException(
                    String.format("Cannot find distinct constructor for type '%s' with parameter types %s",
                            type, Arrays.toString(clazzes)));
        }
        constructor = candidates.get(0);
    }

    //do we really need this dependency?
    //ReflectionUtils.makeAccessible(constructor);
    if (constructor != null && !constructor.isAccessible())
        constructor.setAccessible(true);

    return constructor;

}

From source file:android.support.design.widget.CoordinatorLayout.java

static Behavior parseBehavior(Context context, AttributeSet attrs, String name) {
    if (TextUtils.isEmpty(name)) {
        return null;
    }//from w  w w  .ja v a 2 s  .co m

    final String fullName;
    if (name.startsWith(".")) {
        // Relative to the app package. Prepend the app package name.
        fullName = context.getPackageName() + name;
    } else if (name.indexOf('.') >= 0) {
        // Fully qualified package name.
        fullName = name;
    } else {
        // Assume stock behavior in this package (if we have one)
        fullName = !TextUtils.isEmpty(WIDGET_PACKAGE_NAME) ? (WIDGET_PACKAGE_NAME + '.' + name) : name;
    }

    try {
        Map<String, Constructor<Behavior>> constructors = sConstructors.get();
        if (constructors == null) {
            constructors = new HashMap<>();
            sConstructors.set(constructors);
        }
        Constructor<Behavior> c = constructors.get(fullName);
        if (c == null) {
            final Class<Behavior> clazz = (Class<Behavior>) Class.forName(fullName, true,
                    context.getClassLoader());
            c = clazz.getConstructor(CONSTRUCTOR_PARAMS);
            c.setAccessible(true);
            constructors.put(fullName, c);
        }
        return c.newInstance(context, attrs);
    } catch (Exception e) {
        throw new RuntimeException("Could not inflate Behavior subclass " + fullName, e);
    }
}

From source file:jp.co.acroquest.jsonic.JSON.java

protected <T> T create(Context context, Class<? extends T> c) throws Exception {
    Object instance = null;/*from  www . java  2 s. c om*/

    JSONHint hint = context.getHint();
    if (hint != null && hint.type() != Object.class)
        c = hint.type().asSubclass(c);

    if (c.isInterface()) {
        if (SortedMap.class.equals(c)) {
            instance = new TreeMap<Object, Object>();
        } else if (Map.class.equals(c)) {
            instance = new LinkedHashMap<Object, Object>();
        } else if (SortedSet.class.equals(c)) {
            instance = new TreeSet<Object>();
        } else if (Set.class.equals(c)) {
            instance = new LinkedHashSet<Object>();
        } else if (List.class.equals(c)) {
            instance = new ArrayList<Object>();
        } else if (Collection.class.equals(c)) {
            instance = new ArrayList<Object>();
        } else if (Appendable.class.equals(c)) {
            instance = new StringBuilder();
        }
    } else if (Modifier.isAbstract(c.getModifiers())) {
        if (Calendar.class.equals(c)) {
            instance = Calendar.getInstance();
        }
    } else if ((c.isMemberClass() || c.isAnonymousClass()) && !Modifier.isStatic(c.getModifiers())) {
        Class<?> eClass = c.getEnclosingClass();
        Constructor<?> con = c.getDeclaredConstructor(eClass);
        con.setAccessible(true);
        if (context.contextObject != null && eClass.isAssignableFrom(context.contextObject.getClass())) {
            instance = con.newInstance(context.contextObject);
        } else {
            instance = con.newInstance((Object) null);
        }
    } else {
        if (Date.class.isAssignableFrom(c)) {
            try {
                Constructor<?> con = c.getDeclaredConstructor(long.class);
                con.setAccessible(true);
                instance = con.newInstance(0l);
            } catch (NoSuchMethodException e) {
                // no handle
            }
        }

        if (instance == null) {
            Constructor<?> con = c.getDeclaredConstructor();
            con.setAccessible(true);
            instance = con.newInstance();
        }
    }

    return c.cast(instance);
}

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

/**
 * {@link jp.furplag.util.commons.NumberUtils.NumberObject}
 *///from   www  .  ja v 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:org.apache.geode.internal.InternalDataSerializer.java

private static Object readDataSerializableFixedID(final DataInput in)
        throws IOException, ClassNotFoundException {
    Class c = readClass(in);/*from w  ww  .j  a  va 2  s. com*/
    try {
        Constructor init = c.getConstructor(new Class[0]);
        init.setAccessible(true);
        Object o = init.newInstance(new Object[0]);

        invokeFromData(o, in);

        if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
            logger.trace(LogMarker.SERIALIZER, "Read DataSerializableFixedID {}", o);
        }

        return o;

    } catch (Exception ex) {
        throw new SerializationException(LocalizedStrings.DataSerializer_COULD_NOT_CREATE_AN_INSTANCE_OF_0
                .toLocalizedString(c.getName()), ex);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

private static Object readDataSerializable(final DataInput in) throws IOException, ClassNotFoundException {
    Class c = readClass(in);// w  ww .  j  a va2 s . c  o  m
    try {
        Constructor init = c.getConstructor(new Class[0]);
        init.setAccessible(true);
        Object o = init.newInstance(new Object[0]);
        Assert.assertTrue(o instanceof DataSerializable);
        invokeFromData(o, in);

        if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
            logger.trace(LogMarker.SERIALIZER, "Read DataSerializable {}", o);
        }

        return o;

    } catch (EOFException ex) {
        // client went away - ignore
        throw ex;
    } catch (Exception ex) {
        throw new SerializationException(LocalizedStrings.DataSerializer_COULD_NOT_CREATE_AN_INSTANCE_OF_0
                .toLocalizedString(c.getName()), ex);
    }
}