java 中的instanceof 的理解

java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。

用法:
result = object instanceof class
result = this instanceof class
参数:
Result:布尔类型。
Object:必选项。任意对象表达式。
Class:必选项。任意已定义的对象类

import org.apache.commons.lang.StringUtils;

public class TestFather {

    /**
     * @description: 测试调父类or调子类
     * @param requestAddr
     * @date 2018年7月6日
     * @author tanglijun
     */
    public void testFatherOrChild(String requestAddr) {

        System.out.println(this.getClass().getName());

        try {
//           if (this instanceof TestFather) 
            if (StringUtils.isBlank(requestAddr)) {
                // 子类转父类
                if (this.getClass().equals(TestFather.class)) {
                    this.test();
                } else {
                    TestFather holder = (TestFather) this.getClass().getSuperclass().newInstance();
                    holder.test();
                }
            } else {
                this.test();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void test() {
        System.out.println("father");
    }

    public static void main(String[] args) {
        try {
            TestFather testb = TestChild.class.newInstance();
            testb.testFatherOrChild("1");

            TestFather testC = (TestFather) testb.getClass().getSuperclass().newInstance();
            testC.testFatherOrChild(null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class TestChild extends TestFather{

    @Override
    public void test() {
        System.out.println("child");
    }

}

猜你喜欢

转载自blog.csdn.net/u012794505/article/details/80940155
今日推荐