LoginSignup
5
4

More than 5 years have passed since last update.

instanceOfとgetClassの比較

Posted at

初めに

instanceOfは知っているが、やりたいことができるか検証してみたときの残骸です。
ついでに、equalsのオーバーライド時に、instanceOfとgetClass()のどちらで実装しようか、考える機会があったので比較してみました。
我ながら、instanceOfなんて今更だな-、と思いつつ。

クラスの定義

InstanceOfTest.java
private interface Interface{}

private class ClassBase{}

private class ClassSub extends ClassBase{}

private class ClassInterface extends ClassBase implements Interface{}

//    ClassBase     Inferface
//    ↑       ↑        ↑
// ClassSub   ClassInterface


結果

InstanceOfTest.java
@Test
public void instanceOf(){
    // 同じClassBase型として、宣言する
    ClassBase base = new ClassBase();
    ClassBase sub = new ClassSub();
    ClassBase inter = new ClassInterface();

    assertThat(base instanceof Interface, is(false));
    assertThat(sub instanceof Interface, is(false));
    assertThat(inter instanceof Interface, is(true));

    Class classTest = sub.getClass();
    assertThat(classTest.isInstance(base), is(false));
    assertThat(classTest.isInstance(sub), is(true));
    assertThat(classTest.isInstance(inter), is(false));

    assertThat(sub.getClass() == ClassSub.class, is(true));
    assertThat(sub.getClass() == ClassBase.class, is(false));
    assertThat(sub instanceof ClassBase, is(true));
    assertThat(sub instanceof ClassSub, is(true));

    assertThat(iClass instanceof Interface, is(true));
    assertThat(iClass instanceof ClassInterface, is(true));
    assertThat(iClass instanceof ClassBase, is(true));
    assertThat(iInter instanceof Interface, is(true));
    assertThat(iInter instanceof ClassBase, is(false));
}

で、何をやりたかったかというと

データの内容に問題がないか検証するメソッドをChain of Responsibilityパターン(以下、CoRと略す)で実装した。基本データの内容だけで検討するのだが、後の要件でデータの生成方法によって、チェック項目が追加されることになった。できれば今更データの型を修正したくないので、生成時にチェックする内容をデータ自体にもCoRのチェックとして使用しているinterfaceの実装として持たせました。そして「チェックする内容が追加されたクラス」かを判断し内容を検証するResponsibilityを追加しました。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4