Class.isInstance vs Class.isAssignableFrom and instanceof

Class.isInstance vs Class.isAssignableFrom and instanceof

1. Introduction

In this quick tutorial, we’re going to take a look at the difference between instanceof, Class.isInstance, and Class.isAssignableFrom. We’ll learn how to use each method and what the differences are between them.

2. Setup

Let’s set up an interface and a couple of classes to use while we explore the instanceof, Class.isInstance, and Class.isAssignableFrom functionality.

First, let’s define an interface:

Next, let’s define a class that implements Shape:

Now, we’ll create a class that extends Triangle:

3. instanceof

The instanceof keyword is a binary operator, and we can use it to verify whether a certain object is an instance of a given type. Therefore, the result of the operation is either true or false. Additionally, the instanceof keyword is the most common and straightforward way to check if an object subtypes another type.

Let’s use our classes with the instanceof operator:

Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Shape nonspecificShape = null;

assertTrue(shape instanceof Shape);
assertTrue(triangle instanceof Shape);
assertTrue(isoscelesTriangle instanceof Shape);
assertFalse(nonspecificShape instanceof Shape);

assertTrue(shape instanceof Triangle);
assertTrue(triangle instanceof Triangle);
assertTrue(isoscelesTriangle instanceof Triangle);
assertFalse(nonspecificShape instanceof Triangle);

assertFalse(shape instanceof IsoscelesTriangle);
assertFalse(triangle instanceof IsoscelesTriangle);
assertTrue(isoscelesTriangle instanceof IsoscelesTriangle);
assertFalse(nonspecificShape instanceof IsoscelesTriangle);

With the above code snippet, we can see that the right-hand side type is more generic than the left-hand side object. More specifically, the instanceof operator will process null values to false.

4. Class.isInstance

The isInstance method on the Class class is equivalent to the instanceof operator. The isInstance method was introduced in Java 1.1 because it can be used dynamically. Generally, this method will return true if the argument isn’t null and can be successfully cast to the reference type without raising a ClassCastException.

Let’s look at how we can use the isInstance method with the interface and classes we defined:

Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();
Shape nonspecificShape = null;

assertTrue(Shape.class.isInstance(shape));
assertTrue(Shape.class.isInstance(triangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle));
assertTrue(Shape.class.isInstance(isoscelesTriangle2));
assertFalse(Shape.class.isInstance(nonspecificShape));

assertTrue(Triangle.class.isInstance(shape));
assertTrue(Triangle.class.isInstance(triangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle));
assertTrue(Triangle.class.isInstance(isoscelesTriangle2));

assertFalse(IsoscelesTriangle.class.isInstance(shape));
assertFalse(IsoscelesTriangle.class.isInstance(triangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle));
assertTrue(IsoscelesTriangle.class.isInstance(isoscelesTriangle2));

As we can see, the right-hand side can be equivalent to or more specific than the left-hand side. In particular, providing null to the isInstance method returns false.

5. Class.isAssignableFrom

The Class.isAssignableFrom method will return true if the Class on the left-hand side of the statement is the same as or is a superclass or superinterface of the provided Class parameter.

Let’s use our classes with the isAssignableFrom method:

Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Triangle isoscelesTriangle2 = new IsoscelesTriangle();

assertFalse(shape.getClass().isAssignableFrom(Shape.class));
assertTrue(shape.getClass().isAssignableFrom(shape.getClass()));
assertTrue(shape.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(shape.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));

assertFalse(triangle.getClass().isAssignableFrom(Shape.class));
assertTrue(triangle.getClass().isAssignableFrom(shape.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(triangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));

assertFalse(isoscelesTriangle.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));

assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(Shape.class));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(shape.getClass()));
assertFalse(isoscelesTriangle2.getClass().isAssignableFrom(triangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle.getClass()));
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));

As with the isInstance example, we can clearly see that the right-hand side must be either the same or more specific than the left-hand side. We can also see that we’re never able to assign our Shape interface.

6. The Differences

Now that we’ve laid out a few detailed examples, let’s go over some of the differences.

6.1. Semantical Differences

Superficially, instanceof is a Java Language keyword. In contrast, both isInstance and isAssignableFrom are native methods from Class type.

Semantically, we use them to verify the different relationships between two programming elements:

  • Two objects: we can test if the two objects are identical or equal.
  • An object and a type: we can check whether the object is an instance of the type. Obviously, both the instanceof keyword and the isInstance method belong to this category.
  • Two types: we can examine whether one type is compatible with another type, such as the isAssignableFrom method.

6.2. Usage Corner Case Differences

Firstly, they differ with a null value:

assertFalse(null instanceof Shape);
assertFalse(Shape.class.isInstance(null));
assertFalse(Shape.class.isAssignableFrom(null)); // NullPointerException

From the code snippet above, both instanceof and isInstance return false; however, the isAssignableFrom method throws NullPointerException.

Secondly, they differ with primitive types:

assertFalse(10 instanceof int); // illegal
assertFalse(int.class.isInstance(10));
assertTrue(Integer.class.isInstance(10));
assertTrue(int.class.isAssignableFrom(int.class));
assertFalse(float.class.isAssignableFrom(int.class));

As we can see, the instanceof keyword doesn’t support primitive types. If we use the isInstance method with an int value, the Java compiler will transform the int value into an Integer object. So, the isInstance method supports primitive types but always returns false. When we use the isAssignableFrom method, the result depends on the exact type values.

Thirdly, they differ with class instance variables:

Shape shape = new Triangle();
Triangle triangle = new Triangle();
Class<?> clazz = shape.getClass();

assertFalse(triangle instanceof clazz); // illegal
assertTrue(clazz.isInstance(triangle));
assertTrue(clazz.isAssignableFrom(triangle.getClass()));

From the code snippet above, we realize that both isInstance and isAssignableFrom methods support the class instance variables, but the instanceof keyword doesn’t.

6.3. Bytecode Differences

In a compiled class file, they utilize different opcodes:

  • The instanceof keyword corresponds to the instanceof opcode
  • Both the isInstance and isAssignableFrom methods will use the invokevirtual opcode

In the JVM Instruction Set, the instanceof opcode has a value of 193, and it has a two-byte operand:

instanceof
indexbyte1
indexbyte2

Then, the JVM will compute (indexbyte1 << 8) | indexbyte2 into an index. And this index points to the run-time constant pool of the current class. At the index, the run-time constant pool contains a symbolic reference to a CONSTANT_Class_info constant. And, this constant is exactly the value that the right-hand side of the instanceof keyword needs.

Furthermore, it also explains why the instanceof keyword can’t use the class instance variable. This is because the instanceof opcode needs a constant type in the run-time constant pool, and we can’t replace a constant type with a class instance variable.

And, where is the left-hand side object information of the instanceof keyword stored? It’s on the top of the operand stack. So, the instanceof keyword requires an object on the operand stack and a constant type in the run-time constant pool.

In the JVM Instruction Set, the invokevirtual opcode has a value of 182, and it also has a two-byte operand:

invokevirtual
indexbyte1
indexbyte2

Similarly, the JVM will calculate (indexbyte1 << 8) | indexbyte2 into an index. At the index, the run-time constant pool holds a symbolic reference to a CONSTANT_Methodref_info constant. This constant contains the target method information, such as class name, method name, and method descriptor.

The isInstance method requires two elements on the operand stack: The first element is the type; the second element is the object. However, the isAssignableFrom method requires two type elements on the operand stack.

6.4. Summing Up

In summary, let’s use a table to illustrate their differences:

PropertyinstanceofClass.isInstanceClass.isAssignableFrom
Kindkeywordnative methodnative method
OperandsAn object and a typeA type and an objectOne type and another type
Null handlingfalsefalseNullPointerException
Primitive typesNot SupportedSupported, but always falseYes
Class instance variableNoYesYes
Bytecodeinstanceofinvokevirtualinvokevirtual
Most suitable whenThe object is given, type is known at compile timeThe object is given, the target type is not known at compile typeNo object is given, only types are known and only at runtime
Use casesDaily use, suitable for the majority of casesComplex and untypical cases such as implementing a library or a utility with the use of Reflection API

7. Conclusion

In this tutorial, we looked at the instanceof, Class.isInstance, and Class.isAssignableFrom methods and explored their usage and differences.

As always, the example code for this tutorial can be found over on GitHub.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值