简体   繁体   中英

How to judge boolean equals to Boolean or long equals to Long in java?

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?

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.

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, ie Boolean.class is not equal to Boolean.TYPE (the Class object representing the primitive type boolean ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM