📅  最后修改于: 2023-12-03 15:16:34.094000             🧑  作者: Mango
在Java中,我们使用isAssignableFrom()方法来判断一个类能否被另一个类所赋值。该方法是判定传入的Class参数所表示的类或接口是否与此类对象所表示的类或接口相同,或是否是其超类或超接口。
public boolean isAssignableFrom(Class<?> cls)
如果cls表示的类或接口与此类对象所表示的类或接口相同,或者是此类的超类或接口,则返回true,否则返回false。
public class Animal {
}
public class Dog extends Animal {
}
public static void main(String[] args) {
boolean isAssignableFrom;
isAssignableFrom = Animal.class.isAssignableFrom(Animal.class);
System.out.println("Animal can be assigned from Animal: " + isAssignableFrom);
isAssignableFrom = Dog.class.isAssignableFrom(Animal.class);
System.out.println("Animal can be assigned from Dog: " + isAssignableFrom);
isAssignableFrom = Animal.class.isAssignableFrom(Dog.class);
System.out.println("Dog can be assigned from Animal: " + isAssignableFrom);
}
以上代码的输出结果如下:
Animal can be assigned from Animal: true
Animal can be assigned from Dog: false
Dog can be assigned from Animal: true
从输出结果来看,我们可以得到以下结论: