(new yy())
instanceofxx.class 判斷 yy對(duì)象 否是 xx類 的實(shí)例
xx.class.isAssignableFrom(yy.class) 判斷 yy類 是否為 xx類 的子類或?qū)崿F(xiàn)
/**
* 兩個(gè)Class判斷
*/
// 判斷對(duì)象是否為實(shí)例
ChildClass child = new ChildClass();
System.out.printf("child對(duì)象 是不是 ChildClass 的實(shí)例 %s\n",
child instanceof ChildClass);
// true
System.out.printf("child對(duì)象 是不是 FatherClass 的實(shí)例 %s\n",
child instanceof FatherClass);
// true
// 判斷類是否繼承某類
System.out.printf("FatherClass 是不是 ChildClass 的父類 %s\n",
FatherClass.class.isAssignableFrom(ChildClass.class));
// true
/**
* 接口和實(shí)現(xiàn)類判斷
*/
// 判斷對(duì)象是否為實(shí)例
AbstractInterfaceImpl impl = new AbstractInterfaceImpl();
System.out.printf("impl對(duì)象 是不是 AbstractInterfaceImpl 的實(shí)例 %s\n",
impl instanceof AbstractInterfaceImpl);
// true
System.out.printf("impl對(duì)象 是不是 AbstractInterface 的實(shí)例 %s\n",
impl instanceof AbstractInterface);
// true
// 判斷類是否為接口實(shí)現(xiàn)
System.out.printf("AbstractInterfaceImpl 是不是 AbstractInterface 的接口實(shí)現(xiàn) %s\n",
AbstractInterface.class.isAssignableFrom(AbstractInterfaceImpl.class));
// true