instanceOf

检查的是一个实例是否是某个特定类型的实例;只可将其与命名类型去比较,而不能与Class对象去比较
image.png

  1. public class InstanOfApp2 {
  2. public static void main(String[] args) {
  3. Pet pet = new Pet();
  4. Dog dog = new Dog();
  5. Pug pug = new Pug();
  6. if(pug instanceof Pet){
  7. System.out.println("pug是Pet的一个实例");
  8. }
  9. if(pug instanceof Dog){
  10. System.out.println("put也是Dog的一个实例");
  11. }
  12. }
  13. }

动态的instanceOf

扩展性比较好

  1. Pet.class.isInstance(pet);
  2. isInstance 判断的是该类的是否属于一支继承体系
  3. public class InstanOfApp2 {
  4. public static void main(String[] args) {
  5. Pet pet = new Pet();
  6. Dog dog = new Dog();
  7. Pug pug = new Pug();
  8. testIsInstance(dog);
  9. }
  10. //在扩展Pet继承体系的时候 isInstance 就是执行该类职责的开关
  11. public static void testIsInstance(Pet p){
  12. Class<? extends Pet> pets = Pet.class;
  13. if(pets.isInstance(p))
  14. System.out.println("Pet类的一个实例是:"+p.getClass().getSimpleName());
  15. }
  16. }

扩展例子

public interface Fair {
}

public abstract class Seller implements Fair{
    public void sell(){}
}

public class SuperMarketSeller extends Seller{
    @Override
    public void sell() {
        System.out.println("实体店卖东西");
    }
}
public class EletcSeller extends Seller{
    @Override
    public void sell() {
        System.out.println("通过网站卖东西");
    }
}
public class PeopleApp {
    public static void testSuperMarket(Fair fair) throws Exception{
        Class<? extends Seller> sellerClass = Seller.class;
        if(sellerClass.isInstance(fair)) {
            Method sell = sellerClass.getMethod("sell");
            sell.invoke(fair);
            System.out.println("做一些的其他的活动");
        }
    }
     public static void main(String[] args) throws Exception {
        SuperMarketSeller marketSeller = new SuperMarketSeller();
        //testSuperMarket(marketSeller);
        final EletcSeller eletcSeller = new EletcSeller();
        testSuperMarket(eletcSeller);
    }
}