Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

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

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java

private void set(Object obj, XmlParser.Node node) throws ClassNotFoundException, NoSuchMethodException,
        InvocationTargetException, IllegalAccessException {
    String attr = node.getAttribute("name");
    String name = "set" + attr.substring(0, 1).toUpperCase() + attr.substring(1);
    Object value = value(obj, node);
    Object[] arg = { value };/*  w  ww. jav a  2 s.c  om*/

    Class oClass = nodeClass(node);
    if (oClass != null)
        obj = null;
    else
        oClass = obj.getClass();

    Class[] vClass = { Object.class };
    if (value != null)
        vClass[0] = value.getClass();

    if (log.isDebugEnabled())
        log.debug(obj + "." + name + "(" + vClass[0] + " " + value + ")");

    // Try for trivial match
    try {
        Method set = oClass.getMethod(name, vClass);
        set.invoke(obj, arg);
        return;
    } catch (IllegalArgumentException e) {
        LogSupport.ignore(log, e);
    } catch (IllegalAccessException e) {
        LogSupport.ignore(log, e);
    } catch (NoSuchMethodException e) {
        LogSupport.ignore(log, e);
    }

    // Try for native match
    try {
        Field type = vClass[0].getField("TYPE");
        vClass[0] = (Class) type.get(null);
        Method set = oClass.getMethod(name, vClass);
        set.invoke(obj, arg);
        return;
    } catch (NoSuchFieldException e) {
        LogSupport.ignore(log, e);
    } catch (IllegalArgumentException e) {
        LogSupport.ignore(log, e);
    } catch (IllegalAccessException e) {
        LogSupport.ignore(log, e);
    } catch (NoSuchMethodException e) {
        LogSupport.ignore(log, e);
    }

    // Try a field
    try {
        Field field = oClass.getField(attr);
        if (Modifier.isPublic(field.getModifiers())) {
            field.set(obj, value);
            return;
        }
    } catch (NoSuchFieldException e) {
        LogSupport.ignore(log, e);
    }

    // Search for a match by trying all the set methods
    Method[] sets = oClass.getMethods();
    Method set = null;
    for (int s = 0; sets != null && s < sets.length; s++) {
        if (name.equals(sets[s].getName()) && sets[s].getParameterTypes().length == 1) {
            // lets try it
            try {
                set = sets[s];
                sets[s].invoke(obj, arg);
                return;
            } catch (IllegalArgumentException e) {
                LogSupport.ignore(log, e);
            } catch (IllegalAccessException e) {
                LogSupport.ignore(log, e);
            }
        }
    }

    // Try converting the arg to the last set found.
    if (set != null) {
        try {
            Class sClass = set.getParameterTypes()[0];
            if (sClass.isPrimitive()) {
                for (int t = 0; t < __primitives.length; t++) {
                    if (sClass.equals(__primitives[t])) {
                        sClass = __primitiveHolders[t];
                        break;
                    }
                }
            }
            Constructor cons = sClass.getConstructor(vClass);
            arg[0] = cons.newInstance(arg);
            set.invoke(obj, arg);
            return;
        } catch (NoSuchMethodException e) {
            LogSupport.ignore(log, e);
        } catch (IllegalAccessException e) {
            LogSupport.ignore(log, e);
        } catch (InstantiationException e) {
            LogSupport.ignore(log, e);
        }
    }

    // No Joy
    throw new NoSuchMethodException(oClass + "." + name + "(" + vClass[0] + ")");
}

From source file:org.datacleaner.util.convert.StandardTypeConverter.java

@Override
public Object fromString(Class<?> type, String str) {
    if (ReflectionUtils.isString(type)) {
        return str;
    }/* w w  w.j  a va  2s. c o m*/
    if (ReflectionUtils.isBoolean(type)) {
        return Boolean.valueOf(str);
    }
    if (ReflectionUtils.isCharacter(type)) {
        return Character.valueOf(str.charAt(0));
    }
    if (ReflectionUtils.isInteger(type)) {
        return Integer.valueOf(str);
    }
    if (ReflectionUtils.isLong(type)) {
        return Long.valueOf(str);
    }
    if (ReflectionUtils.isByte(type)) {
        return Byte.valueOf(str);
    }
    if (ReflectionUtils.isShort(type)) {
        return Short.valueOf(str);
    }
    if (ReflectionUtils.isDouble(type)) {
        return Double.valueOf(str);
    }
    if (ReflectionUtils.isFloat(type)) {
        return Float.valueOf(str);
    }
    if (ReflectionUtils.is(type, Class.class)) {
        try {
            return Class.forName(str);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Class not found: " + str, e);
        }
    }
    if (ReflectionUtils.is(type, EnumerationValue.class)) {
        return new EnumerationValue(str);
    }
    if (type.isEnum()) {
        try {
            Object[] enumConstants = type.getEnumConstants();

            // first look for enum constant matches
            Method nameMethod = Enum.class.getMethod("name");
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                if (name.equals(str)) {
                    return e;
                }
            }

            // check for aliased enums
            for (Object e : enumConstants) {
                String name = (String) nameMethod.invoke(e);
                Field field = type.getField(name);
                Alias alias = ReflectionUtils.getAnnotation(field, Alias.class);
                if (alias != null) {
                    String[] aliasValues = alias.value();
                    for (String aliasValue : aliasValues) {
                        if (aliasValue.equals(str)) {
                            return e;
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("Unexpected error occurred while examining enum", e);
        }
        throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName());
    }
    if (ReflectionUtils.isDate(type)) {
        return toDate(str);
    }
    if (ReflectionUtils.is(type, File.class)) {
        final FileResolver fileResolver = new FileResolver(_configuration);
        return fileResolver.toFile(str);
    }
    if (ReflectionUtils.is(type, Calendar.class)) {
        Date date = toDate(str);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }
    if (ReflectionUtils.is(type, Pattern.class)) {
        try {
            return Pattern.compile(str);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e);
        }
    }
    if (ReflectionUtils.is(type, java.sql.Date.class)) {
        Date date = toDate(str);
        return new java.sql.Date(date.getTime());
    }
    if (ReflectionUtils.isNumber(type)) {
        return ConvertToNumberTransformer.transformValue(str);
    }
    if (ReflectionUtils.is(type, Serializable.class)) {
        logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName());
        byte[] bytes = (byte[]) _parentConverter.fromString(byte[].class, str);
        ChangeAwareObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes));
            objectInputStream.addClassLoader(type.getClassLoader());
            Object obj = objectInputStream.readObject();
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException("Could not deserialize to " + type + ".", e);
        } finally {
            FileHelper.safeClose(objectInputStream);
        }
    }

    throw new IllegalArgumentException("Could not convert to type: " + type.getName());
}

From source file:com.yahoo.elide.core.PersistentResource.java

/**
 * Invoke the set[fieldName] method on the target object OR set the field with the corresponding name.
 * @param fieldName the field name to set or invoke equivalent set method
 * @param value the value to set/*  ww  w  . j av a  2s. c o m*/
 */
protected void setValue(String fieldName, Object value) {
    Class<?> targetClass = obj.getClass();
    try {
        Class<?> fieldClass = dictionary.getType(targetClass, fieldName);
        String realName = dictionary.getNameFromAlias(obj, fieldName);
        fieldName = (realName != null) ? realName : fieldName;
        String setMethod = "set" + WordUtils.capitalize(fieldName);
        Method method = EntityDictionary.findMethod(targetClass, setMethod, fieldClass);
        method.invoke(obj, coerce(value, fieldName, fieldClass));
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new InvalidAttributeException(fieldName, type);
    } catch (IllegalArgumentException | NoSuchMethodException noMethod) {
        try {
            Field field = targetClass.getField(fieldName);
            field.set(obj, coerce(value, fieldName, field.getType()));
        } catch (NoSuchFieldException | IllegalAccessException noField) {
            throw new InvalidAttributeException(fieldName, type);
        }
    }

    runTriggers(OnUpdate.class, fieldName);
    this.requestScope.queueCommitTrigger(this, fieldName);
}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

@Override
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype,
        ArgumentMatches matches) {//from   w  ww . j a va  2s .co m
    Class type = makeRawTypeIfNecessary(fulltype);
    if (source.isFlag())
        return true;

    ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source);
    ArgumentMatchValue value = getArgumentValue(defaultDefinition, matches);
    Object result;
    Tags tags = getArgumentTags(matches);

    // lets go through the types we support
    try {
        if (type.isPrimitive()) {
            Method valueOf = primitiveToWrapperMap.get(type).getMethod("valueOf", String.class);
            if (value == null)
                throw new MissingArgumentValueException(createDefaultArgumentDefinition(source));
            result = valueOf.invoke(null, value.asString().trim());
        } else if (type.isEnum()) {
            Object[] vals = type.getEnumConstants();
            Object defaultEnumeration = null; // as we look at options, record the default option if it exists
            for (Object val : vals) {
                if (String.valueOf(val).equalsIgnoreCase(value == null ? null : value.asString()))
                    return val;
                try {
                    if (type.getField(val.toString()).isAnnotationPresent(EnumerationArgumentDefault.class))
                        defaultEnumeration = val;
                } catch (NoSuchFieldException e) {
                    throw new ReviewedStingException(
                            "parsing " + type.toString() + "doesn't contain the field " + val.toString());
                }
            }
            // if their argument has no value (null), and there's a default, return that default for the enum value
            if (defaultEnumeration != null && value == null)
                result = defaultEnumeration;
            // if their argument has no value and there's no default, throw a missing argument value exception.
            // TODO: Clean this up so that null values never make it to this point.  To fix this, we'll have to clean up the implementation of -U.
            else if (value == null)
                throw new MissingArgumentValueException(createDefaultArgumentDefinition(source));
            else
                throw new UnknownEnumeratedValueException(createDefaultArgumentDefinition(source),
                        value.asString());
        } else if (type.equals(File.class)) {
            result = value == null ? null : value.asFile();
        } else {
            Constructor ctor = type.getConstructor(String.class);
            result = ctor.newInstance(value == null ? null : value.asString());
        }
    } catch (UserException e) {
        throw e;
    } catch (InvocationTargetException e) {
        throw new UserException.CommandLineException(String.format(
                "Failed to parse value %s for argument %s.  This is most commonly caused by providing an incorrect data type (e.g. a double when an int is required)",
                value, source.field.getName()));
    } catch (Exception e) {
        throw new DynamicClassResolutionException(String.class, e);
    }

    // TODO FIXME!

    // WARNING: Side effect!
    parsingEngine.addTags(result, tags);

    return result;
}

From source file:maimeng.yodian.app.client.android.chat.activity.ChatActivity.java

/**
 * ?gridview?view//from   ww  w.j  a v  a  2  s.com
 *
 * @param i
 * @return
 */
private View getGridChildView(int i) {
    View view = View.inflate(this, R.layout.expression_gridview, null);
    ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
    List<String> list = new ArrayList<String>();
    if (i == 1) {
        List<String> list1 = reslist.subList(0, 20);
        list.addAll(list1);
    } else if (i == 2) {
        list.addAll(reslist.subList(20, reslist.size()));
    }
    list.add("delete_expression");
    final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
    gv.setAdapter(expressionAdapter);
    gv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String filename = expressionAdapter.getItem(position);
            try {
                // ????
                // ?????
                if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                    if (filename != "delete_expression") { // ?
                        // ????SmileUtils
                        Class clz = Class.forName("maimeng.yodian.app.client.android.chat.utils.SmileUtils");
                        Field field = clz.getField(filename);
                        mEditTextContent
                                .append(SmileUtils.getSmiledText(ChatActivity.this, (String) field.get(null)));
                    } else { // 
                        if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                            int selectionStart = mEditTextContent.getSelectionStart();// ??
                            if (selectionStart > 0) {
                                String body = mEditTextContent.getText().toString();
                                String tempStr = body.substring(0, selectionStart);
                                int i = tempStr.lastIndexOf("[");// ???
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i, selectionStart);
                                    if (SmileUtils.containsKey(cs.toString()))
                                        mEditTextContent.getEditableText().delete(i, selectionStart);
                                    else
                                        mEditTextContent.getEditableText().delete(selectionStart - 1,
                                                selectionStart);
                                } else {
                                    mEditTextContent.getEditableText().delete(selectionStart - 1,
                                            selectionStart);
                                }
                            }
                        }

                    }
                }
            } catch (Exception e) {
            }

        }
    });
    return view;
}

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 w  w w.j a v  a2 s  .  c om
@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:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#compareTo(java.lang.Number, java.lang.Number)}.
 */// w w w  .j  a v  a  2 s .  c o  m
@SuppressWarnings("unchecked")
@Test
public void testCompareToNumberNumber() {
    assertEquals("null", (Object) 0, compareTo(null, null));
    assertEquals("null", (Object) 1, compareTo(1, null));
    assertEquals("null", (Object) 1, compareTo(-1, null));
    assertEquals("null", (Object) 1, compareTo(Float.NEGATIVE_INFINITY, null));
    assertEquals("null", (Object) (-1), compareTo(null, 1));
    assertEquals("null", (Object) (-1), compareTo(null, -1));
    assertEquals("null", (Object) (-1), compareTo(null, Double.NEGATIVE_INFINITY));
    assertEquals("Infinity", (Object) 0, compareTo(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY));
    assertEquals("Infinity", (Object) 0, compareTo(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
    assertEquals("NaN", (Object) 1, compareTo(Float.NaN, null));
    assertEquals("NaN", (Object) 1, compareTo(Float.NaN, 1));
    assertEquals("NaN", (Object) 1, compareTo(Float.NaN, -1));
    assertEquals("NaN", (Object) 1, compareTo(Float.NaN, Double.POSITIVE_INFINITY));
    assertEquals("NaN", (Object) 0, compareTo(Float.NaN, Double.NaN));
    assertEquals("NaN", (Object) (-1), compareTo(null, Double.NaN));
    assertEquals("NaN", (Object) (-1), compareTo(1, Double.NaN));
    assertEquals("NaN", (Object) (-1), compareTo(-1, Double.NaN));
    assertEquals("NaN", (Object) (-1), compareTo(Float.NEGATIVE_INFINITY, Double.NaN));
    assertEquals("NaN", (Object) 0, compareTo(Double.NaN, Float.NaN));
    for (Class<?> type : NUMBERS) {
        Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
        try {
            Number n = null;
            if (ClassUtils.isPrimitiveWrapper(type)) {
                n = (Number) wrapper.getField("MAX_VALUE").get(null);
            } else {
                n = INFINITY_DOUBLE.pow(2);
                if (BigInteger.class.equals(type))
                    n = ((BigDecimal) n).toBigInteger();
            }
            assertEquals("equals: " + type.getSimpleName(), 0, compareTo(n, new BigDecimal(n.toString())));
        } 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#valueOf(java.lang.Object, java.lang.Class)}.
 *//*ww  w .  j a  va2  s  .co  m*/
@SuppressWarnings("unchecked")
@Test
public void testValueOfObjectClassOfT() {
    assertEquals("null", valueOf(null, null, false), valueOf(null, null));
    try {
        for (Class<?> type : NUMBERS) {
            Object o = null;
            assertEquals("null: " + type.getSimpleName(), valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = Float.NaN;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = Double.NaN;
            assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "1");
                } else {
                    o = valueType.getField("ONE").get(null);
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "-123");
                } else {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("-123");
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            for (Class<?> valueType : OBJECTS) {
                if (ObjectUtils.isAny(valueType, Double.class, Float.class)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "123.456");
                } else if (BigDecimal.class.equals(valueType)) {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("123.456");
                } else {
                    continue;
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            for (Class<?> valueType : OBJECTS) {
                if (ObjectUtils.isAny(valueType, Double.class, Float.class)) {
                    o = valueType.getMethod("valueOf", String.class).invoke(null, "-123.456");
                } else if (BigDecimal.class.equals(valueType)) {
                    Constructor<?> c = valueType.getDeclaredConstructor(String.class);
                    o = c.newInstance("-123.456");
                } else {
                    continue;
                }
                assertEquals(o + "(" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        valueOf(o, (Class<? extends Number>) type, false),
                        valueOf(o, (Class<? extends Number>) type));
            }

            o = INFINITY_DOUBLE.pow(2);
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = INFINITY_DOUBLE.pow(2).negate();
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = INFINITY_DOUBLE.pow(2).toBigInteger();
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = INFINITY_DOUBLE.pow(2).toBigInteger().negate();
            assertEquals("Huge: (" + o.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "1";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "-123456E-3";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "Infinity";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));

            o = "-Infinity";
            assertEquals("\"" + o + "\": " + type.getSimpleName(),
                    valueOf(o, (Class<? extends Number>) type, false),
                    valueOf(o, (Class<? extends Number>) type));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:org.apache.asterix.om.typecomputer.ExceptionTest.java

private void testTypeComputer(Class<? extends IResultTypeComputer> c) throws Exception {
    // Mocks the type environment.
    IVariableTypeEnvironment mockTypeEnv = mock(IVariableTypeEnvironment.class);
    // Mocks the metadata provider.
    IMetadataProvider<?, ?> mockMetadataProvider = mock(IMetadataProvider.class);

    // Mocks function expression.
    AbstractFunctionCallExpression mockExpr = mock(AbstractFunctionCallExpression.class);
    FunctionIdentifier fid = mock(FunctionIdentifier.class);
    when(mockExpr.getFunctionIdentifier()).thenReturn(fid);
    when(fid.getName()).thenReturn("testFunction");

    int numCombination = (int) Math.pow(ATypeTag.values().length, 2);
    // Sets two arguments for the mocked function expression.
    for (int index = 0; index < numCombination; ++index) {
        try {/*from   w w w . j  a v a2s .  c om*/
            List<Mutable<ILogicalExpression>> argRefs = new ArrayList<>();
            for (int argIndex = 0; argIndex < 2; ++argIndex) {
                int base = (int) Math.pow(ATypeTag.values().length, argIndex);
                ILogicalExpression mockArg = mock(ILogicalExpression.class);
                argRefs.add(new MutableObject<>(mockArg));
                IAType mockType = mock(IAType.class);
                when(mockTypeEnv.getType(mockArg)).thenReturn(mockType);
                int serializedTypeTag = (index / base) % ATypeTag.values().length + 1;
                ATypeTag typeTag = ATypeTag.VALUE_TYPE_MAPPING[serializedTypeTag];
                if (typeTag == null) {
                    // For some reason, type tag 39 does not exist.
                    typeTag = ATypeTag.ANY;
                }
                when(mockType.getTypeTag()).thenReturn(typeTag);
            }

            // Sets up arguments for the mocked expression.
            when(mockExpr.getArguments()).thenReturn(argRefs);

            // Sets up required/actual types of the mocked expression.
            Object[] opaqueParameters = new Object[2];
            opaqueParameters[0] = BuiltinType.ANY;
            opaqueParameters[1] = BuiltinType.ANY;
            when(mockExpr.getOpaqueParameters()).thenReturn(opaqueParameters);

            // Invokes a type computer.
            IResultTypeComputer instance = (IResultTypeComputer) c.getField("INSTANCE").get(null);
            instance.computeType(mockExpr, mockTypeEnv, mockMetadataProvider);
        } catch (AlgebricksException ae) {
            String msg = ae.getMessage();
            if (msg.startsWith("ASX")) {
                // Verifies the error code.
                int errorCode = Integer.parseInt(msg.substring(3, 7));
                Assert.assertTrue(errorCode >= 1000 && errorCode < 2000);
                continue;
            } else {
                // Any root-level compilation exceptions thrown from type computers should have an error code.
                Assert.assertTrue(!(ae instanceof AlgebricksException) || (ae.getCause() != null));
            }
        } catch (ClassCastException e) {
            continue;
        }
    }
}

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)}.
 *///from  w  w w.  j av  a  2s .  c  o  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()));
    }
}