instanceof:是RTTI的第三种方式,用来告诉我们对象是不是某个特定类型的实例,使用时只可将其与命名类型去比较,而不能与Class对象去比较。

  1. package com.package14;
  2. import com.zx.chapter11.pets.Dog;
  3. import com.zx.chapter11.pets.Pet;
  4. import com.zx.chapter11.pets.Pug;
  5. public class InstanceofDemo01 {
  6. public static void main(String[] args) {
  7. Pet pet = new Pet();
  8. Dog dog = new Dog();
  9. Pug pug = new Pug();
  10. if (pug instanceof Pet){
  11. System.out.println("pug是pet的一个实例");
  12. }
  13. if (dog instanceof Pet){
  14. System.out.println("dog是pet的一个实例");
  15. }
  16. }
  17. }

14.3类型转换前先做检查 - 图1

动态的instanceOf:

比instanod的扩展性高

  1. package com.package14;
  2. import com.zx.chapter11.pets.Dog;
  3. import com.zx.chapter11.pets.Pet;
  4. import com.zx.chapter11.pets.Pug;
  5. public class InstanceofDemo02 {
  6. public static void main(String[] args) {
  7. Pet pet = new Pet();
  8. Dog dog = new Dog();
  9. Pug pug = new Pug();
  10. test(dog);
  11. test(pug);
  12. }
  13. static void test(Pet p){
  14. Class<Pet> petClass = Pet.class;
  15. if (petClass.isInstance(p)){
  16. System.out.println(p+"是pet的一个实例");
  17. }
  18. }
  19. }

应用:

  1. public interface Fari {//通过接口做一个判断,看是否实现了接口
  2. }
  1. package com.package14;
  2. public abstract class Seller implements Fari {//实现了接口,则所以的子类也实现了Fari接口
  3. public void sell(){};
  4. }
  5. class SuperMakeretSeller extends Seller{
  6. @Override
  7. public void sell() {
  8. System.out.println("到实体店买东西");
  9. }
  10. }
  11. class ElentcSeller extends Seller{
  12. @Override
  13. public void sell() {
  14. System.out.println("网上购物");
  15. }
  16. }
  1. package com.package14;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. public class SellerApp {
  5. static void test(Fari fari) throws Exception {
  6. Class<? extends Seller> sellerClass = Seller.class;
  7. if (sellerClass.isInstance(fari)){
  8. Method sell = sellerClass.getMethod("sell");
  9. sell.invoke(fari);
  10. System.out.println("做活动");
  11. }
  12. }
  13. public static void main(String[] args) throws Exception {
  14. ElentcSeller elentcSeller = new ElentcSeller();
  15. test(elentcSeller);
  16. }
  17. }