백엔드 (Back-End)/자바 ( JAVA )

[JAVA] Object 클래스와 toString()메서드

xxvigrufv 2022. 9. 4. 22:13
반응형

자바의 Object 클래스는 모든 자바 클래스의 최상위 클래스 입니다. 

java.lang.Object  이다. 

 

VO 또는 DTO를 출력하게 되면  가끔씩 "패키지명@난수"와 같은 형태로 출력되는 것을 볼 수 있다. 
이것은 Java Object로 되어 있는 상태를 바로 로그로 찍어보기 때문이다. 

 

Object.toString() 은 
클래스 이름, @ 기호, 16진수의 해시코드로 구현됩니다.

// Object.toString()의 구현코드
public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

 

// 로그 찍어보기
log.debug(myObject.toString());

// Result
com.xxvigrfuv.workathome.ObjectExplain@3f92ewon => 반출
public class Animals {
  String animalName;
  String animalTitle;

  Animals (int animalName, String animalTitle) {
    this.animalName = animalName;
    this.animalTitle = animalTitle;
    }
  }

public class toStringEx {
  public static void main (String[] args) {
    Animals animals = new Animals("sonny","개미");

    System.out.println(animals);
    System.out.println(animals.toString());
    }
}

/* 출력결과
object.Animals@23ou592j
object.Animals@23ou592j
*/



com.xxvigrfuv.workathome ====> 클래스 이름 
com.xxvigrfuv.workathome 패키지에 있는  ObjectExplain 이라는 클래스
@ => 문자열을 결합하는 역할 3f92ewon 객체의 해시 코드,

 

반응형