Yanny
Yanny

Reputation: 198

How to check if Class<Object> is castable to class

How can I check if Class<Object> stores class that can be casted to another class, e.g. String? I tried to use clazz.isInstance(String.class), but this check always return true, because e.g. String is instance of Object.

Note that I cant use instanceof.

Upvotes: 0

Views: 595

Answers (1)

Strikegently
Strikegently

Reputation: 2461

You're looking for isAssignableFrom

A String is an Object but an Object is not necessarily a String. So Object is assignable from String, but not the other way around.

class Scratch {
    public static void main(String[] args) {
        System.out.println(Object.class.isAssignableFrom(String.class)); //true
        System.out.println(String.class.isAssignableFrom(Object.class)); //false
    }
}

Upvotes: 2

Related Questions