Java在静态方法外设置私有属性

时间:2015-01-17 06:21:30

标签: java

我刚注意到一些对我没有意义的事情。

请使用以下代码:

public class User {
    private String name = "";

    public User() {}

    public static User fromJson(JSONObject json) {
        User user = new User();

        user.name = json.optString("name", "");
        System.out.println("Name = " + user.getName());
        // Will print: "Name = THEGIVENNAME"

        return user;
    }

    public String getName() { return this.name; }
    public String setName(String name) { this.name = name; }
}

如果我尝试访问User.fromJson包之外的方法User,当我执行user.getName()时,它会返回一个空字符串:

public void someMethod() {
    JSONObject json = new JSONObject();

    try {
        json.put("name", "Test Name");
    } catch (JSONException e) { e.printStacktrace(); }

    User user = User.fromJson(json);

    System.out.println("Name = " + user.getName());
    // Will print: "Name = "
}

但是,如果在User.fromJson方法上我使用user.setName()代替user.name =,则可行:

    ...
    public static User fromJson(JSONObject json) {
        User user = new User();

        user.setName(json.optString("name", ""));

        return user;
    }
    ...

然后:

public void someMethod() {
    JSONObject json = new JSONObject();

    try {
        json.put("name", "Test Name");
    } catch (JSONException e) { e.printStacktrace(); }

    User user = User.fromJson(json);

    System.out.println("Name = " + user.getName());
    // Will print: "Name = Test Name"
}

我有什么东西在这里失踪吗?

谢谢。

0 个答案:

没有答案