简体   繁体   English

如何在Java中判断布尔值等于布尔值还是long等于Long?

[英]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) . 我有两种方法,一种是boolean getA() ,另一种是void setA(Boolean a)
I need judge the get method return type is equal to set method param type to do something. 我需要判断get方法的返回类型等于set方法的param类型来做某事。

// 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. booleanBoolean是不同的类型。

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 . 可以通过Boolean.TYPEboolean.class获得boolean类型的运行时表示boolean.class

  • The runtime representation of the type Boolean can be obtained via Boolean.TRUE.getClass() or Boolean.class . Boolean类型的运行时表示形式可以通过Boolean.TRUE.getClass()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. 反射API(通常)不了解用于消除重载方法歧义的JLS规则。

  • When you use Method.invoke , you need to pass a boolean argument wrapped as a Boolean . 使用Method.invoke ,需要传递一个包装为Booleanboolean参数。

The above apply to all primitive types and their respective wrapper types. 以上内容适用于所有原始类型及其各自的包装器类型。

To judge if the types are equal, call equals() : 判断类型是否相等,请调用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 ). 在您的示例中, else子句将执行,因为booleanBoolean不是同一类型,即Boolean.class不等于Boolean.TYPE (表示原始类型 booleanClass对象)。

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: 要将Object转换为基本类型:

bPrimitive = bObject.booleanValue();

Hope this help. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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