Test if object implements interface
To check if an object obj
implements an interface MyInterface
using instanceof:
The implemented
value will be true when obj
adheres to MyInterface
and false otherwise.
Straight to the methods
Let's break down our type checking tools. Like a Swiss Army knife, each method has its own unique utility.
The reflective way
Java's built-in java.lang.Class
provides methods to introspect the type information of objects at runtime using Reflection:
Class.isInstance(Object)
: Is your object an instance of a class or interface?
Class.isAssignableFrom(Class)
: Can an object of your class be assigned to another class?
Class.isInstance(Object)
is nearly equivalent to using instanceof
, but it provides compile-time safety. This method can be preferable when dynamically testing for interface implementation, especially when dealing with generics.
When instanceof
smells fishy 🐠
Overuse of instanceof
can sometimes suggest a potential design flaw. If you often rely on instanceof
checks, consider refining your design to exploit polymorphism or strategy patterns.
Is instanceof
efficient?
If you are iterating over multiple interface checks, Class.isInstance(Object)
would be a more efficient choice, as it can avoid some internal overhead. However, for casual type checks, instanceof
enhances code readability and is easier to use.
How to handle null references
One of the advantages of using instanceof
is its null safety. The operator won't throw any NullPointerException
, even when dealing with null references. This safe check makes handling nulls a breeze:
Emphasizing design principles
If you're continuously checking types or looking to see the interfaces implemented, it might be a sign to reconsider your design principles. Perhaps making better use of generics, single responsibility principle, or liskov substitution principle can eliminate the need for explicit checks.
Was this article helpful?