【问题标题】:Convert instanced object to string将实例化对象转换为字符串
【发布时间】:2017-07-02 20:06:46
【问题描述】:

我初始化了一个 Password 对象,但在将同一对象用作字符串以用于以后的目的(例如计算字符串中的字母数量)时遇到了麻烦。我知道我只使用 String.valueOf.toString 方法获取对象的文本表示。如何获取我的对象传递并获取我初始化它的“hello”字符串?

public class Password {

public Password (String text) {
}

public String getText(){
    String string = String.valueOf(this);
    return string;
}
public static void main (String[] args) {
    Password pass = new Password ("hello");
    System.out.println(pass.toString());
}

}

【问题讨论】:

标签: java string object


【解决方案1】:

您的实际 getText() 方法没有意义:

public String getText(){
    String string = String.valueOf(this);
    return string;
}

您尝试从Password 实例的toString() 方法重新创建String
这真的没有必要(无用的计算)而且很笨拙,因为 toString() 并非旨在提供函数数据。

要达到你的目标,这是非常基础的。

将文本存储在Password 实例的字段中:

public Password (String text) {
  this.text = text;
}

并提供text 字段的视图。

你可以用这种方式替换getText()

public String getText(){    
    return text;
}

【讨论】:

    【解决方案2】:

    使用字段。

    public class Password {
    
        private String text; // This is a member (field) It belongs to each
                                 // Password instance you create.
    
        public Password(String value) {
            this.text = value; // Copy the reference to the text to the field
                               // 'text'
        }
    }
    

    String.valueOf(this) 的问题是thisPassword 实例,valueOf() 方法完全不知道如何将Password 实例转换为字段. You named it "Password", but it could also beMyText@987654329来自上述示例的@MySecret. So you need to tell how aPasswordinstance can be displayed as text. In your case, you'll need to just use thetext` 字段。

    您绝对应该阅读docs about classes。我认为你缺少一些基本的东西。


    注意:由于安全隐患,您也不应该将密码存储到字符串中,但这是另一回事,超出了您的问题范围。

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 2011-08-02
      • 2016-06-10
      相关资源
      最近更新 更多