A contribution for all the other answers, when possible do not use the most upvoted answer of method isAssignableFrom
, even the "not great" answer of using clazz.getInterfaces()
has better performance than isAssignableFrom
.
A common mistake for developers when looking for an answer to the OP question, is to prefer isAssignableFrom
when an instance is available, wrongly doing this:
if (IMyInterface.isAssignableFrom(myObject.getClass())) {
...
When possible, use IMyInterface.class.isInstance
or instanceof
as both of those have way better performance. Of course, as the OP stated; they have the drawback that you must have an instance and not just the class
.
if (IMyInterface.class.isInstance(myObject)) {
...
if (myObject instanceof IMyInterface) { // +0.2% slower than `isInstance` (*see benchmark)
...
An even faster, but ugly solution would be to store an static Set
with all the "valid" classes instead of checking them, this ugly solution is only preferred when you need to test classes a lot, as its performance outperforms all the other approaches for direct class
check.
public static final Set<Class<?>> UGLY_SET = Stream.of(MyClass1.class, MyClass2.class, MyClass3.class).collect(Collectors.toCollection(HashSet::new));
if (UGLY_SET.contains(MyClass)) {
...
(*) JMH Benchmark for +0.2%
Please visit this answer from users @JBE, @Yura and @aleksandr-dubinsky, credits for them. Also, there's plenty of detail in that answer for the benchmark results to not be valid, so please take a look into it.