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. }

扩展例子

  1. public interface Fair {
  2. }
  3. public abstract class Seller implements Fair{
  4. public void sell(){}
  5. }
  6. public class SuperMarketSeller extends Seller{
  7. @Override
  8. public void sell() {
  9. System.out.println("实体店卖东西");
  10. }
  11. }
  12. public class EletcSeller extends Seller{
  13. @Override
  14. public void sell() {
  15. System.out.println("通过网站卖东西");
  16. }
  17. }
  18. public class PeopleApp {
  19. public static void testSuperMarket(Fair fair) throws Exception{
  20. Class<? extends Seller> sellerClass = Seller.class;
  21. if(sellerClass.isInstance(fair)) {
  22. Method sell = sellerClass.getMethod("sell");
  23. sell.invoke(fair);
  24. System.out.println("做一些的其他的活动");
  25. }
  26. }
  27. public static void main(String[] args) throws Exception {
  28. SuperMarketSeller marketSeller = new SuperMarketSeller();
  29. //testSuperMarket(marketSeller);
  30. final EletcSeller eletcSeller = new EletcSeller();
  31. testSuperMarket(eletcSeller);
  32. }
  33. }