簡體   English   中英

JAVA:使用變量的 class 的動態 object 屬性

[英]JAVA: dynamic object property of a class using a variable

我正在通過在線課程學習 OOP 和 java。 本章是關於訪問修飾符的,您必須調用 TestRobot 的所有可能屬性。

現在我已經用一組屬性進行了嘗試,並想使用一個 for 循環來檢查它們是否存在。 當然,我可以只做 4 次,但這在某種程度上是多余的。 :D 現在我有一個錯誤,沒有符號屬性。 我的建議是編譯器正在檢查 class 機器人的“屬性”。

是否有可能告訴 java 屬性是 class 終端的數組或變量,而不是 class 機器人本身的一部分? 例如,在 JavaScript 中,您只需編寫robots[attributes[i]]

甚至可以調用 class 的每個屬性嗎?

class TestRobot {
    private int secretKey = 602413;
    protected int numberOfProcessorCores = 4;
    boolean hasFirewall = false;
    public String id = "58-08-2";
}


class Terminal {
    String[] attributes = {"secretKey", "numberOfProcessorCores", "hasFirewall", "id"};
    
    public void hackRobot(TestRobot robot) {
        for(int i = 0; i < attributes.length; i++){
            if(robot.attributes[i]) {
                System.out.println(attributes[i]);
            }
        }
    }
}

是的,這可以通過反射 API來實現。 您可以使用TestRobot.class.getDeclaredAttributes()動態獲取屬性列表,然后您可以以編程方式檢查每個字段的類型、其可見性,並且您可以在TestRobot實例上獲取/設置這些屬性的值。

暫無
暫無

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

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