program story

Java에서 toString ()을 올바르게 재정의하는 방법은 무엇입니까?

inputbox 2020. 10. 12. 07:30
반응형

Java에서 toString ()을 올바르게 재정의하는 방법은 무엇입니까?


조금 어리석은 것 같지만 toString()방법 에 대한 도움이 필요 하고 매우 짜증납니다. 온라인 검색을 시도한 이유는 toString"키드 생성자 # 2를 찾지 못함"인데도 불구하고 엉망이 된 곳이고 다른 작업을하려고하는데 작동하지 않기 때문입니다. 좋아, 그래서 여기 내 코드가 있습니다.

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 위의 toString (내 세 번째 매개 변수가 꺼져 있고 String이어야 함)가 꺼져 있습니다. 세 번째 값을 하드 코딩하면 문제가 발생하고 찾을 수 없다고 말합니다 (위에서). 그렇다면 어떻게 날짜를 얻고 그것을 깰 수 있습니까?

이것을 부르는 클래스는 다음과 같습니다.

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  

여러 생성자를 조사했지만 실제로 도움이되지 않았습니다. 나는 toString()방법을 조사 하고 이전에 toString()만든 이전 방법 논리를 사용해 보았지만 이것은 완전히 새로운 것이므로 작동하지 않았습니다.

도움?


toString를 반환 할 예정이다 String.

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

toString방법 을 생성하기 위해 IDE의 기능을 사용하는 것이 좋습니다 . 직접 코딩하지 마십시오.

예를 들어 Eclipse는 소스 코드를 마우스 오른쪽 버튼으로 클릭하고 Source > Generate toString


Java toString () 메서드

객체를 문자열로 표현하려면 toString () 메서드가 존재합니다.

toString () 메서드는 객체의 문자열 표현을 반환합니다.

객체를 인쇄하는 경우 Java 컴파일러는 객체에서 toString () 메서드를 내부적으로 호출합니다. 따라서 toString () 메서드를 재정의하고 원하는 출력을 반환합니다. 이는 구현에 따라 객체의 상태 등이 될 수 있습니다.

Java toString () 메소드의 장점

Object 클래스의 toString () 메서드를 재정의하면 객체의 값을 반환 할 수 있으므로 많은 코드를 작성할 필요가 없습니다.

toString () 메서드없이 출력

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를 인쇄하면 개체의 Hashcode 값이 인쇄되지만 이러한 개체의 값을 인쇄하고 싶습니다. Java 컴파일러는 내부적으로 toString () 메서드를 호출하므로이 메서드를 재정의하면 지정된 값이 반환됩니다. 아래 주어진 예를 통해 이해합시다.

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

toString ()은 대부분 Java의 다형성 개념과 관련이 있습니다. Eclipse에서 toString ()을 클릭하고 마우스 오른쪽 버튼을 클릭 한 다음 Open Declaration을 클릭하고 수퍼 클래스 toString ()의 출처를 확인합니다.


toString ()에서 새 객체를 만들 수 있습니다. 사용하다

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

대신에

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

필요에 따라 반환 문자열을 변경할 수 있습니다. calander 대신 날짜를 저장하는 다른 방법이 있습니다.


일반 메서드 인 것처럼 생성자를 호출 할 수 없습니다 new. 새 개체를 만들려면 로만 호출 할 수 있습니다 .

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

그러나 toString () 메서드에서 새 객체를 생성하는 것은 원하는 작업이 아닙니다.


다음 코드는 샘플입니다. IDE 기반 변환을 사용하는 대신 동일한 기반의 질문으로 구현하는 더 빠른 방법이있어 향후 변경 사항이 발생하여 값을 반복해서 수정할 필요가 없습니까?

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

실제로 toString은 문자열을 반환해야하기 때문에 이와 같은 것을 반환해야합니다.

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

그리고 실제로 생성자에서 잘못된 작업을 수행하고 반대 작업을 수행해야하는 동안 사용자가 이름에 설정 한 변수를 설정합니다. 하지 말아야 할 것

n = this.name

해야 할 일

this.name = n

감사합니다.


클래스에 새로운 String 객체를 생성하고 생성자에서 원하는 것을 할당하고 재정의 된 toString 메서드에서 반환함으로써 이와 같이 작성할 수도 있습니다.

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()  
 }  
}

단위 테스트에 관심이 있다면 공용 "ToStringTemplate"을 선언 한 다음 toString을 단위 테스트 할 수 있습니다. 단위 테스트를하지 않더라도 "깨끗한"것으로 생각하고 String.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를 만들고, 속성을 설정하고, ToStringTemplate에서 자신 만의 string.format을 수행하고 비교하여 단위 테스트를 할 수 있습니다.

making ToStringTemplate static-final means "ONE VERSION" of the truth, rather than having a "copy" of the template in the unit-test.


As others explained, the toString is not the place to be instantiating your class. Instead, the toString method is intended to build a string representing the value of an instance of your class, reporting on at least the most important fields of data stored in that object. In most cases, toString is used for debugging and logging, not for your business logic.

StringJoiner

As of Java 8 and later, the most modern way to implement toString would use the StringJoiner class.

Something like this:

@Override
public String toString ()
{
    return new StringJoiner( " | " , Person.class.getSimpleName() + "[ " , " ]" )
            .add( "name=" + name )
            .add( "phone=" + phone )
            .toString();
}

Person[ name=Alice | phone=555.867.5309 ]


The best way in my opinion is using google gson library:

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

or apache commons lang reflection way


  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 
    

    -click on override toString method here you will get options to select what type of variables you want to select.

참고URL : https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java

반응형