0

I have a method that is used to compare parameter types to the types of arguments given.

private boolean typesMatch(Class<?>[] one, Object[] two)
{
    if(one.length != two.length)
        return false;

    for (int i = 0; (i < one.length)&&(i < two.length); i++)
        if(!one[i].equals(two[i].getClass()))
            return false;

    return true;
}

For example, in one[], there might be String, boolean. However, in the second, there is String, Boolean. Do you see my issue? When it compares boolean and Boolean it returns false. How do I solve this so that I don't have to use 'if statements' for every primitive type to unwrap them?

Edit: I mean to unwrap the wrapper class in the second array so it's comparable to the primitive type in the first array.

Originally, the Boolean object in array two was added to it as primitive boolean.

Josiah Savoie
  • 135
  • 12

2 Answers2

1

This should resolve your problem:

private static boolean typesMatch(Class<?>[] one, Object[] two)
    {
        if(one.length != two.length) {
            return false;
        }

        for (int i = 0; (i < one.length)&&(i < two.length); i++){
            if ((one[i].isPrimitive() && two[i].getClass().getSimpleName().equalsIgnoreCase(one[i].getName())) ||
                    (two[i].getClass().isPrimitive() && one[i].getSimpleName().equalsIgnoreCase(two[i].getClass().getName()))) {
                return true;
            }
            if(!one[i].equals(two[i].getClass())) {
                return false;
            }
        }

        return true;
    }
cristi
  • 361
  • 3
  • 9
  • The second array will always have wrapped primitives. So using .isPrimitive() on an object in that array will always return false. I will change it so that only if the type in the first array is primitive will their names be compared. But your idea of name comparison was ingenious. +1 – Josiah Savoie Jul 03 '14 at 21:54
0

You don't need if statement for every primitive.

Just check if two[i].getClass() is one of primitives, and then call function which will return it's wrapper class.

// safe because both Long.class and long.class are of type Class<Long>
  @SuppressWarnings("unchecked")
  private static <T> Class<T> wrap(Class<T> c) {
    return c.isPrimitive() ? (Class<T>) WRAPPERS_TO_PRIMITIVES.get(c) : c;
  }

  private static final Map<Class<?>, Class<?>> WRAPPERS_TO_PRIMITIVES
    = new ImmutableMap.Builder<Class<?>, Class<?>>()
      .put(Boolean.class, boolean.class)
      .put(Byte.class, byte.class)
      .put(Character.class, char.class)
      .put(Double.class, double.class)
      .put(Float.class, float.class)
      .put(Integer.class, int.class)
      .put(Long.class, long.class)
      .put(Short.class, short.class)
      .put(Void.class, void.class)
      .build();

The code above is taken from Simple way to get wrapper class type in Java

Community
  • 1
  • 1
Kasper Ziemianek
  • 1,329
  • 8
  • 15