Java isAssignableFrom: How to Use & Examples

The isAssignableFrom method in Java is used to determine if one class can be assigned to another class.

Below is an example code:

public class Main {
    public static void main(String[] args) {
        Class<?> class1 = String.class;
        Class<?> class2 = Object.class;

        if (class1.isAssignableFrom(class2)) {
            System.out.println("class1可以赋值给class2");
        } else {
            System.out.println("class1无法赋值给class2");
        }
    }
}

In the example above, we created two classes, String and Object, and used the isAssignableFrom method to determine if the String class can be assigned to the Object class. Since String is a subclass of Object, the output result is “class1 can be assigned to class2.”

bannerAds