0

I hava two methods, one is boolean getA(), another one is void setA(Boolean a).
I need judge the get method return type is equal to set method param type to do something.

// set method param type
Class<?> paramType = m2.getParameterTypes()[0];
// get method return type
Class<?> returnType = m1.getReturnType();

How can I judge these two type equal?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
He Yuntao
  • 86
  • 11
  • 2
    Well, the two types aren't equal, so it's not clear what you want to do. Do you mean that you want to test whether the primitive can be boxed into the non-primitive class? Possibly relevant threads: [Simple way to get wrapper class type in Java](http://stackoverflow.com/q/1704634/535871) and [Dynamically find the class that represents a primitive Java type](http://stackoverflow.com/q/180097/535871) – Ted Hopp Jan 11 '17 at 03:47
  • You can pass them through Guava's [`Primitives.wrap()`](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Primitives.html#wrap(java.lang.Class)) or [`Primitives.unwrap()`](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Primitives.html#unwrap(java.lang.Class)) before comparing them. – shmosel Jan 11 '17 at 04:02
  • @shmosel thanks a lot. You solved my big problem! – He Yuntao Jan 18 '17 at 09:09

3 Answers3

3

The types are not equal. boolean and Boolean are different types.

So if you want to treat them as equal in some (reflective) context, then the logic of your application has to deal with that.

For the record:

  • The runtime representation of the type boolean can be obtained via Boolean.TYPE or boolean.class.

  • The runtime representation of the type Boolean can be obtained via Boolean.TRUE.getClass() or Boolean.class. Note the differences in case!

  • If you lookup a method or constructor reflectively, then you need to provide the correct argument type. The reflection APIs (generally) do not understand the JLS rules for disambiguating overloaded methods.

  • When you use Method.invoke, you need to pass a boolean argument wrapped as a Boolean.

The above apply to all primitive types and their respective wrapper types.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

To judge if the types are equal, call equals():

if (returnType.equals(paramType)) {
    // Same type
} else {
    // Different type
}

In your example, the else clause will execute, because boolean and Boolean are not the same type, i.e. Boolean.class is not equal to Boolean.TYPE (the Class object representing the primitive type boolean).

Andreas
  • 154,647
  • 11
  • 152
  • 247
-1

You mean convert boolean primitive to Boolean object, don't you? To convert primitive to Object:

boolean bPrimitive = true;
Boolean bObject = Boolean.valueOf(bPrimitive);

To convert Object to primitive:

bPrimitive = bObject.booleanValue();

Hope this help.

You're awesome
  • 301
  • 2
  • 16