instanceof、isInstance、isAssignableFrom的区别

时间:2023-03-09 13:22:33
instanceof、isInstance、isAssignableFrom的区别

https://*.com/questions/3949260/java-class-isinstance-vs-class-isassignablefrom

1. MyClass.class.isInstance(obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException. In other words, obj is an instance of MyClass or its subclasses.

2. MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, OtherOther can be a class or an interface. It answers true if Other can be converted to a MyClass.

public class NewMain
{
public static void main(String[] args)
{
NewMain nm = new NewMain();
nm.doit();
} public void doit()
{
A myA = new A();
B myB = new B();
A[] aArr = new A[0];
B[] bArr = new B[0]; System.out.println("b instanceof a: " + (myB instanceof A));
System.out.println("b isInstance a: " + A.class.isInstance(myB));
System.out.println("a isInstance b: " + B.class.isInstance(myA));
System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class));
System.out.println("a isAssignableFrom b: " + B.class.isAssignableFrom(A.class));
System.out.println("bArr isInstance A: " + A.class.isInstance(bArr));
System.out.println("bArr isInstance aArr: " + aArr.getClass().isInstance(bArr));
System.out.println("bArr isAssignableFrom aArr: " + aArr.getClass().isAssignableFrom(bArr.getClass()));
} class A
{
} class B extends A
{
}
}

结果

b instanceof a: true
b isInstance a: true
a isInstance b: false
b isAssignableFrom a: true
a isAssignableFrom b: false
bArr isInstance A: false
bArr isInstance aArr: true
bArr isAssignableFrom aArr: true