isAssignableFrom & isInstance

java.lang.Object extended by java.lang.Class
  • boolean isAssignableFrom(Class cls) : Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
  • boolean isInstance(Object obj) : Determines if the specified Object is assignment-compatible with the object represented by this Class.


isAssignableFrom接受的是Class参数,isInstance接受的是Object参数。
		System.out.println("Object.class.isAssignableFrom(String.class) = " + Object.class.isAssignableFrom(String.class));
		System.out.println("Object.class.isAssignableFrom(Object.class) = " + Object.class.isAssignableFrom(Object.class));
		System.out.println("String.class.isAssignableFrom(Object.class) = " + String.class.isAssignableFrom(Object.class));
		
		String s = "";
		Object o = new Object();
		System.out.println("Object.class.isInstance(s) = " + Object.class.isInstance(s));
		System.out.println("Object.class.isInstance(o) = " + Object.class.isInstance(o));
		System.out.println("String.class.isInstance(o) = " + String.class.isInstance(o));

执行结果:
Object.class.isAssignableFrom(String.class) = true
Object.class.isAssignableFrom(Object.class) = true
String.class.isAssignableFrom(Object.class) = false
Object.class.isInstance(s) = true
Object.class.isInstance(o) = true
String.class.isInstance(o) = false

你可能感兴趣的:(instance)