【问题标题】:Android, couldn't make static getter setter property work?Android,不能使静态 getter setter 属性工作吗?
【发布时间】:2016-11-28 19:58:24
【问题描述】:

我正在尝试这个......

public class Info {
    private static Info ourInstance = new Info();
    public static Info getInstance() { return ourInstance; }

    private static int currentIndex;

    public static void setCurrentIndex(int i) {
        Log.d("DEV", "setter!");
        currentIndex = i;
        // do other work here
    }

    public static int getCurrentIndex() {
        Log.d("DEV", "getter!");
        return currentIndex;
    }

    private Info() {
        Log.d("DEV", "class initialized no problem...");
        currentIndex = 42; // just doesn't work, only sets the field
    }

}

在任何其他类...

Info.currentIndex = 666; // just doesn't work

它只是不起作用 - 可能是什么问题?什么都试过了。

【问题讨论】:

    标签: java android properties getter-setter


    【解决方案1】:

    如果你最终要这样做,为什么要定义 setter/getter?

    Info.currentIndex = 666;
    

    如果是这样,则将 currentIndex 可见性更改为 public...

    或者更好的是,与代码一致并执行

    Info.setCurrentIndex(666);
    

    【讨论】:

    • holy - 我完全忘记了 java 并没有给你对 getter/setter 的神奇访问。抱歉浪费了时间!!!!!!!!!!!!!!!!!!谢谢!!!!!!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多