JAvaにおけるinstanceofの理解

3439 ワード

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");
    }

}