instanceof:是RTTI的第三种方式,用来告诉我们对象是不是某个特定类型的实例,使用时只可将其与命名类型去比较,而不能与Class对象去比较。
package com.package14;
import com.zx.chapter11.pets.Dog;
import com.zx.chapter11.pets.Pet;
import com.zx.chapter11.pets.Pug;
public class InstanceofDemo01 {
public static void main(String[] args) {
Pet pet = new Pet();
Dog dog = new Dog();
Pug pug = new Pug();
if (pug instanceof Pet){
System.out.println("pug是pet的一个实例");
}
if (dog instanceof Pet){
System.out.println("dog是pet的一个实例");
}
}
}
动态的instanceOf:
比instanod的扩展性高
package com.package14;
import com.zx.chapter11.pets.Dog;
import com.zx.chapter11.pets.Pet;
import com.zx.chapter11.pets.Pug;
public class InstanceofDemo02 {
public static void main(String[] args) {
Pet pet = new Pet();
Dog dog = new Dog();
Pug pug = new Pug();
test(dog);
test(pug);
}
static void test(Pet p){
Class<Pet> petClass = Pet.class;
if (petClass.isInstance(p)){
System.out.println(p+"是pet的一个实例");
}
}
}
应用:
public interface Fari {//通过接口做一个判断,看是否实现了接口
}
package com.package14;
public abstract class Seller implements Fari {//实现了接口,则所以的子类也实现了Fari接口
public void sell(){};
}
class SuperMakeretSeller extends Seller{
@Override
public void sell() {
System.out.println("到实体店买东西");
}
}
class ElentcSeller extends Seller{
@Override
public void sell() {
System.out.println("网上购物");
}
}
package com.package14;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SellerApp {
static void test(Fari fari) throws Exception {
Class<? extends Seller> sellerClass = Seller.class;
if (sellerClass.isInstance(fari)){
Method sell = sellerClass.getMethod("sell");
sell.invoke(fari);
System.out.println("做活动");
}
}
public static void main(String[] args) throws Exception {
ElentcSeller elentcSeller = new ElentcSeller();
test(elentcSeller);
}
}