I just wonder if there is a good reason or practice of when to use != null
instead of instanceof
to check if something is null.
Is a bad practice to test if something is null with instanceof
?
For example:
View view = ((Activity) context).findViewById(viewID);
if (view instanceof View) {
listener.onView(view, viewID);
}
or
View view = ((Activity) context).findViewById(viewID);
if (view != null) {
listener.onView(view, viewID);
}
Shouldn't it works just as same?
That depends on what you are actually checking
null
, use x == null
and nothing else If you want to know whether a particular reference is not null
and points to an instance of type Foo
you may use x instanceof Foo
as it implies being not null
But if the compile-time type of the reference is already Foo
, you know that the instance is of type Foo
when it is non- null
, therefore the first bullet applies in this case; you just want to test for null
. This is the case in your updated question's example, the reference already has the compile-time type View
.
If you want to know whether a type cast (Foo)x
will succeed, you may use x == null || x instanceof Foo
x == null || x instanceof Foo
as the type cast will also succeed when x
is null
(however, you should think twice whether you really want to accept null
s, even if the type cast will be successful)
Null check is not needed at all to check before instanceof
. If it's null then during check of instanceof it will return false.
Is a bad practice to test if something is null with instanceof
?
During runtime when you are not sure it can be null or not.just simply use instanceof
it will return false in case of null object.
I just wonder if there is a good reason or practice of when to use != null instead of instanceof to check if something is null.
Of course there's a reason, the !=null
can be applied to all objects in Java, but instanceof
can't be applied to Primitive types it only checks if a given object is instance of a class, that's why we use !=null
to check for nullity.
Is a bad practice to test if something is null with instanceof ?
You can use it, but why whould you use instanceof
if it may cause problems with primitive types and if !=null
can be applied to all objects.
EDIT:
In your case using if (view instanceof View)
is much safer because you are using it to test if it's an instance of View
and in the same time if it's not null
.
And as you can see in " Here " you can see that you can use instanceof
to check for nullity.
instanceof
instruction is used to check if an object is an instance of a certain class.
So, using it to check null value simply makes no sense...
In your code snippets you are checking two different things:
View
class So they are not two ways to do the same thing...
Take a look: use of "Instance of" in java
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.