Explain Codes LogoExplain Codes Logo

Test if object implements interface

java
reflection
instanceof
polymorphism
Nikita BarsukovbyNikita Barsukov·Sep 4, 2024
TLDR

To check if an object obj implements an interface MyInterface using instanceof:

boolean implemented = obj instanceof MyInterface; // 'implemented' acts like a bouncer for 'MyInterface' interface party.

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.Classprovides methods to introspect the type information of objects at runtime using Reflection:

  1. Class.isInstance(Object): Is your object an instance of a class or interface?
boolean isInstanceOf = MyInterface.class.isInstance(obj); // Reflection is like looking in the mirror. What do you see? 'MyInterface'
  1. Class.isAssignableFrom(Class): Can an object of your class be assigned to another class?
boolean canBeAssigned = MyInterface.class.isAssignableFrom(obj.getClass()); // 'canBeAssigned' is your class-compatible love match finder 💖.

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.

bool isSerializable = obj instanceof java.io.Serializable; // 'isSerializable' is your own 'ship-in-a-bottle' assessment tool.

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:

MyInterface mi = possiblyNullObject(); boolean isImplemented = mi instanceof MyInterface; // 'isImplemented' is your all-seeing Oracle: null or not null.

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.