私はリフレクションを理解するためにこのコードを書き、コードの動作の理由を実際に理解できなかった1つのシナリオに遭遇しました。うまくいけば、私はコミュニティからいくつかのガイダンスを受け取ります。
以下は私のテストモデルクラスです。ここでは、すべてのインスタンス化について、実行時に(リフレクションを使用して)作成されたインスタンスの正確な数を知りたいです。
public final class Model {
private static final Model instance = new Model("Testing");
private static int count = 0;
private String name;
private Model(String name) {
this.name = name;
++count;
}
public static Model getInstance() {
return instance;
}
public static int getInstanceCount() {
return count;
}
public String getName() {
return name;
}
public void doSomething() {
try {
System.out.println("Shh.... I am trying to do something");
Thread.sleep(1000);
System.out.println("Ok! Done.");
return;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Oops! I failed in doing your job...");
}
}
このシナリオのドライバーコードは次のとおりです。
public class ReflectionTest {
public static void main(String[] args) throws Exception {
Model.getInstance().doSomething();
System.out.println(Model.getInstanceCount());
Constructor<?>[] constructor = Model.class.getDeclaredConstructors();
for (Constructor<?> aConstructor : constructor) {
aConstructor.setAccessible(true);
Model m = (Model) aConstructor.newInstance("Testing through Reflection");
System.out.println(m.getName());
m.doSomething();
System.out.println(m.getInstanceCount());
//System.out.println(Model.getInstanceCount());
}
}
}
上記のコードの出力は次のようになります。
Shh.... I am trying to do something
Ok! Done.
0
Testing through Reflection
Shh.... I am trying to do something
Ok! Done.
1
ご覧のとおり、インスタンス数は1
でした。結果は2であると予想していましたが、テストモデルクラスのコンストラクターを次のように変更しました。countのデータ型は、以前に設定された 'int'ではなく、Integerに変更されました。
private Model(String name) {
this.name = name;
if (count == null)
count = 0;
++count;
}
驚いたことに、インスタンス数の正しい値を取得しています。
Shh.... I am trying to do something
Ok! Done.
1
Testing through Reflection
Shh.... I am trying to do something
Ok! Done.
2
これはばかげた質問かもしれませんが、実際に舞台裏で何が起こったのかについて考えることはできません。これについてコミュニティからのガイダンスが必要です。
前もって感謝します。
これは反射とは関係ありません。
private static final Model instance = new Model("Testing");
private static int count = 0;
初期化子は順番に実行されます。そう:
private static final Model instance = new Model("Testing");
コンストラクターを実行count
すると、0から1にインクリメントされますが、次のようになります。
private static int count = 0;
カウントをゼロに戻します。
宣言の順序を逆にします。
private static int count = 0;
private static final Model instance = new Model("Testing");
または、初期化子を省略しますcount
(デフォルト値はいずれにしてもゼロです)。
private static final Model instance = new Model("Testing");
private static int count;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加