English 中文(简体)
如何正确覆盖到 Java 的 String ()?
原标题:How to override toString() properly in Java?
  • 时间:2012-05-24 08:49:31
  •  标签:
  • java

Sounds a little stupid, but I need help on my toString() method and it is very irking. I tried looking up online because the toString is the one where it is screwing up and "not finding Kid constructor #2" even though it is there and I would even do something else and it doesn t work. Ok that was a lot so here is my code:

import java.util.*; 
   class Kid {  
      String name; 
      double height; 
      GregorianCalendar bDay; 

      public Kid () { 
         this.name = "HEAD";
         this.height = 1; 
         this.bDay = new GregorianCalendar(1111,1,1); 
      } 

      public Kid (String n, double h, String date) {
      // method that toString() can t find somehow
         StringTokenizer st = new StringTokenizer(date, "/", true);
         n = this.name;
         h = this.height;
      } 

      public String toString() { 
         return Kid(this.name, this.height, this.bDay);
      } 
   } //end class 

Ok,所以我上面的线条(我知道,我的第三个参数关闭了,应该是一个字符串)关闭了。如果我硬码了第三个参数的值,它就会变得干燥,说它找不到(上面的)这个(上面的)。所以我怎样才能找到日期并打破它呢?

班级呼叫这里在下面

class Driver {   
   public static void main (String[] args) {   
      Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");   
      System.out.println(kid1.toString());
   } //end main method 
} //end class  

I tried researching multiple constructors and it really didn t help. I tried researching toString() methods, and tried using previous toString() methods logic that I created previous but this is brand new so it never worked.

帮助?

最佳回答

to string 应该是返回 string

public String toString() { 
    return "Name:  " + this.name + " , Height:  " + this.height + " , Birthday:  " + this.bDay + " ";
} 

我建议您使用您的 IDE 特性生成 < code> to String 方法。 不要手动编码它 。

例如,如果您只要右键点击源代码并选择 源代码 & gt; 生成到 string , 剪贴板就可以这样做

问题回答

Java to String () 方法

如果您想要将任何对象作为字符串表示, String () 方法就会存在。

到 String () 的方法返回对象的字符串表达式 。

如果您打印任何对象, Java 编译器内部会在该对象上引用到 String () 方法。因此, 超越到 String () 方法, 返回想要的输出, 可以是对象的状态等, 取决于您是否执行 。

Advantage of Java to String () 方法

超越对象类的 String () 方法, 我们可以返回对象的值, 所以不需要写入很多代码 。

没有 String () 方法的输出输出

class Student{  
 int id;  
 String name;  
 String address;  

 Student(int id, String name, String address){  
 this.id=id;  
 this.name=name;  
 this.address=address;  
 }  

 public static void main(String args[]){  
   Student s1=new Student(100,”Joe”,”success”);  
   Student s2=new Student(50,”Jeff”,”fail”);  

   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
}  

Output:Student@2kaa9dc
       Student@4bbc148

您可以看到以上示例 # 1 。 打印 s1 和 s2 打印对象的散记值, 但我想要打印这些对象的值。 由于 java 编译器内部呼叫 String () 方法, 此方法将返回指定值。 请用下面的示例来理解 :

Example#2

Output with overriding toString() method

class Student{  
 int id;  
 String name;  
 String address;  

 Student(int id, String name, String address){  
 this.id=id;  
 this.name=name;  
 this.address=address;  
 }  

//overriding the toString() method  
public String toString(){ 
  return id+" "+name+" "+address;  
 }  
 public static void main(String args[]){  
   Student s1=new Student(100,”Joe”,”success”);  
   Student s2=new Student(50,”Jeff”,”fail”);  

   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
} 

Output:100 Joe success
       50 Jeff fail

Note that toString() mostly is related to the concept of polymorphism in Java. In, Eclipse, try to click on toString() and right click on it.Then, click on Open Declaration and see where the Superclass toString() comes from.

正如其他解释的那样, toString 并不是要对您的类进行即时处理的地方。 相反, to String 方法旨在构建一个字符串,代表您类实例的价值,至少报告该对象中存储的最重要的数据领域。 在多数情况下, tostring 用于 debugging blog ,而不是用于您的 business逻辑 (一些历史方法除外,如 Integer.toString() )。

要生成显示对象值的文本, 请添加另一种方法 。 人们通常会命名方法, 比如 get DisplayName 。 例如, < a href="https://docs. oracle.com/ en/javase/11docs/ api/java. bas/java/ time/ Dayofweek. html# getdisplayName (java.time. format. TextStyle,java. util. locale)" rel=“ noferrererer” {code> Dayofweek:: get DisplayName res://docs. oracle. com/ java/javaso/11docs/api/java. base/time/ month.html# getplayName (java.tile. stol.

StringJoiner

在爪哇8及以后,实施to String 的最现代方法将使用 StringJoiner 类。正如医生所说:

StringJoiner 用于构建字符序列,字符序列由分隔符分隔开来,可选从提供的前缀开始,以提供的后缀结束。

像这样使用 :

@Override
public String toString ()
{
    return new StringJoiner(                           // In Java 8 and later, StringJoiner 用于构建字符序列,字符序列由分隔符分隔开来,可选从提供的前缀开始,以提供的后缀结束。
                " | " ,                                // Delimiter
                Person.class.getSimpleName() + "[ " ,  // Prefix
                " ]"                                   // Suffix
            )
            .add( "name=" + name )                     // Append
            .add( "phone=" + phone )                   // Append
            .toString();                               // Convert entire sequence to a single `String` object.
}

个人[姓名=爱丽丝 电话=555.867.5309]

record

Java 16为简单界定一个主要目的是以透明和不可改变的方式交流数据的类别带来了一个新的方式:record

您仅通过列出每个成员字段的类型和名称来定义记录。 编译者暗含创建构建器、 获取器、 evols & amp; hashCode to String

Default implementation of toString

to string 的默认执行包括每个成员字段。

public Kid ( String name , double height , LocalDate birthDate ) {} 

和任何其他物体一样有证据

Kid alice = new Kid( "Alice" , 6.1d , LocalDate.of( 2019 , Month.April , 23 ) ) ;
String output = alice.toString() ;

您可以选择用自己的软件来取代默认执行 。 通常不需要覆盖, 因为记录的目的是作为简单的数据存储器 。

You can creating new object in the toString(). use

return "Name = " + this.name +" height= " + this.height;

代替

return Kid(this.name, this.height, this.bDay);

您可以根据需要更改返回字符串。 存在其它存储日期而非卡兰德的方法 。

无法调用构建器, 仿佛这是一个正常的方法, 您只能用 < code> new 来调用它来创建新对象 :

Kid newKid = new Kid(this.name, this.height, this.bDay);

但从您的 String () 方法构建新对象并非您想要做的 。

我认为最好的方法就是利用谷歌Ghson图书馆:

        @Override
public String toString() {
    return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}

或apache 平民 朗声反射方式

以下的代码是一个样本。 基于同一代码的问题, 而不是使用基于 IDE 的转换, 是否有更快的方法可以执行, 以便将来发生更改, 我们不需要一次又一次地修改数值?

@Override
    public String toString() {
        return "ContractDTO{" +
                "contractId= " + contractId +     +
                ", contractTemplateId= " + contractTemplateId +     +
                 } ;
    }

如果您对单位测试感兴趣, 那么您可以公开宣布“ 切换板板块 ”, 然后单位测试您的单位 。 即使您不单位测试它, 我认为它“ 清洁” 并使用字符串. format 。

public class Kid {

    public static final String ToStringTemplate = "KidName= %1s , Height= %2s , GregCalendar= %3s ";

    private String kidName;
    private double height;
    private GregorianCalendar gregCalendar;

    public String getKidName() {
        return kidName;
    }

    public void setKidName(String kidName) {
        this.kidName = kidName;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public GregorianCalendar getGregCalendar() {
        return gregCalendar;
    }

    public void setGregCalendar(GregorianCalendar gregCalendar) {
        this.gregCalendar = gregCalendar;
    }

    public String toString() { 
        return String.format(ToStringTemplate, this.getKidName(), this.getHeight(), this.getGregCalendar());
    } 
}

现在您可以通过创建 Kid 来进行单位测试, 设置属性, 并在 ToString Template 上做您自己的字符串. format 和比较 。

制 String Template 静态终局, 意指真实的“ one VERSION ”, 而不是单位测试中的模板的“ 复制件 ” 。

实际上你需要还回这样的东西 因为String得还一个字符串

public String toString() {
 return "Name :" + this.name + "whatever :" + this.whatever + "";
}

and you actually do something wrong in the constructer you set the variable the user set to the name while you need to do the opposite. What you shouldn t do

n = this.name

你该做什么

this.name = n

希望这有助感谢

我们甚至可以在类中创建一个新的字符串对象, 并将其分配为在构建器中我们所想要的, 然后返回到被推翻的 String 方法, 这样我们甚至可以写成这样 。

public class Student{  
 int id;  
 String name;  
 String address;  
 String details;
 Student(int id, String name, String address){  
 this.id=id;  
 this.name=name;  
 this.address=address;  
 this.details=id+"  "+name+"  "+address;  
 }  

//overriding the toString() method  
public String toString(){ 
  return details;  
 }  
 public static void main(String args[]){  
   Student s1=new Student(100,"Joe","success");  
   Student s2=new Student(50,"Jeff","fail");  

   System.out.println(s1);//compiler writes here s1.toString()  
   System.out.println(s2);//compiler writes here s2.toString()  
 }  
}

Nice and concise way is to use Lombok annotations. It has @ToString annotation, which will generate an implementation of the toString() method. By default, it will print your class name, along with each field, in order, separated by commas. You can easily customize your output by passing parameters to annotation, e.g.:

@ToString(of = {"name", "lastName"})

相当于纯爪哇:

public String toString() {
        return "Person(name=" + this.name + ", lastName=" + this.experienceInYears + ")";
    }

如果您只是使用 toString () 来调试 < a href=> "https://stackoverflow.com/q/1051182/86967>> >DTO , 您可以自动生成 人类可读 输出, 其方式如下:

import com.fasterxml.jackson.databind.ObjectMapper;
...
public String toString() {
    try { return new ObjectMapper().writeValueAsString(this); }
    catch (Exception e) { return "{ObjectMapper failed}"; }
}

然而,如果 DTO 可能含有 PII (不应记录在日志中), 这不适合生产部署。

Always have easy way: Right Click > Generate > toString() > select template that you want. enter image description here

  1. if you are use using notepad: then

    public String toString(){
    
     return ""; ---now here you can use variables which you have created for your class
    
    }
    
  2. if you are using eclipse IDE then press

    -alt +shift +s 
    

    - 点击 over 转到 String 方法, 您可以选择您要选择的变量类型 。

But then in the toString() method you aren t actually returning a String, are you? You ll have to return a String for this method to work.

public String toString() {
  return "Name : " + this.name + " Height : " + this.height + " BirthDay : " + this.bday;
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...