簡體   English   中英

了解反射的奇怪行為

[英]Understanding reflection's strange behavior

我正在編寫這段代碼來理解反射,並遇到了一個我無法真正弄清楚代碼行為的原因的場景。 希望我能得到社區的一些指導。
以下是我的測試 model class & 在這里,對於每個實例化,我想知道在運行時創建的實例的確切數量(使用反射)

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

上面這段代碼的 output 出來如下,

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。
但是,我更改了測試 model 類的構造函數,如下所示。 count 的數據類型現在更改為 Integer,而不是之前設置的 'int'

    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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM