Java로 객체 인쇄

Mohammad Irfan 2023년10월12일
  1. 개체 출력 이해
  2. Java에서 객체 인쇄
  3. 배열 객체
  4. 개체를 인쇄하는 방법?
  5. 배열 객체 인쇄
  6. 다차원 배열 객체 인쇄
  7. Java에서 컬렉션 개체 인쇄
  8. Apache Commons 라이브러리 사용
  9. 요약
Java로 객체 인쇄

이 자습서에서는 Java로 개체를 인쇄하는 방법을 소개하고 주제를 이해하기 위한 몇 가지 예제 코드를 나열합니다.

객체는 클래스의 인스턴스이며 클래스 속성 및 메서드에 액세스하는 데 사용할 수 있습니다. 그러나 System.out.println() 메서드를 사용하여 개체를 인쇄하려고 하면 예상한 출력을 얻지 못할 수 있습니다. 디버그하고 모든 것이 제대로 작동하는지 확인하기 위해 객체 속성을 인쇄하는 경우가 많습니다. 이 자습서에서는 Java에서 개체 속성을 인쇄하는 방법을 배웁니다.

개체 출력 이해

개체 정보

  • 물체를 인쇄할 때 어떤 일이 일어나는지 이해하려고 노력해 봅시다. System.out.print() 메서드를 호출하면 Object 클래스의 toString() 메서드가 호출됩니다.
  • 우리가 알고 있듯이 Java의 모든 클래스는 Object 클래스를 확장합니다. 따라서 toString() 메서드는 모든 클래스의 모든 인스턴스에 적용할 수 있습니다.
  • 이 메서드는 클래스 이름과 객체의 해시 코드로 구성된 문자열을 반환합니다. 이 둘은 @ 기호로 연결됩니다.

Java에서 객체 인쇄

새 클래스를 만들고 해당 개체를 인쇄해 보겠습니다.

class Student {
  private String studentName;
  private int regNo;
  private Double gpa;
  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
}
public class Demo {
  public static void main(String[] args) {
    Student s1 = new Student("Justin", 101, 8.81);
    Student s2 = new Student("Jessica", 102, 9.11);
    System.out.println(s1);
    System.out.println(s2);
  }
}

출력:

Student@7a81197d
Student@5ca881b5

출력의 첫 번째 부분에는 클래스 이름(이 경우 Student)이 표시되고 두 번째 부분에는 개체에 대한 고유한 해시 코드가 표시됩니다. 위의 코드를 실행할 때마다 다른 해시코드를 얻게 됩니다.

배열 객체

배열은 Java의 객체이기도 하며 콘솔에 배열을 인쇄하려고 할 때 요소를 얻지 못합니다. 다음 코드를 실행하고 출력을 살펴보겠습니다.

public class Demo {
  public static void main(String[] args) {
    int[] integerArr = {5, 10, 15};
    double[] doubleArr = {5.0, 10.0, 15.0};
    char[] charArr = {'A', 'B', 'C'};
    String[] stringArr = {"Justin", "Jessica"};
    int[][] twoDimArray = {{1, 2, 3}, {4, 5, 6}};
    System.out.println("Integer Array:" + integerArr);
    System.out.println("Double Array:" + doubleArr);
    System.out.println("Char Array:" + charArr);
    System.out.println("String Array:" + stringArr);
    System.out.println("2D Array:" + twoDimArray);
  }
}

출력:

Integer Array:[I@36baf30c
Double Array:[D@7a81197d
Char Array:[C@5ca881b5
String Array:[Ljava.lang.String;@24d46ca6
2D Array:[[I@4517d9a3
  • 대괄호는 배열의 차원을 나타냅니다. 1차원 배열의 경우 단일 여는 대괄호가 인쇄됩니다. 2차원 배열의 경우 두 개의 대괄호가 있습니다.
  • 대괄호 뒤의 다음 문자는 배열에 저장된 내용을 나타냅니다. 정수 배열의 경우 I이 인쇄됩니다. char 배열의 경우 문자 C가 인쇄됩니다.
  • 문자열 배열의 L은 배열에 클래스의 개체가 포함되어 있음을 나타냅니다. 이러한 경우 클래스 이름이 다음(여기서는 java.lang.String)으로 인쇄됩니다.
  • @ 기호 뒤에 개체의 해시 코드가 인쇄됩니다.

개체를 인쇄하는 방법?

객체와 그 속성을 다른 형식으로 인쇄하려면 클래스의 toString() 메서드를 재정의해야 합니다. 이 메서드는 문자열을 반환해야 합니다. Student 클래스에서 이 메서드를 재정의하고 프로세스를 이해해 보겠습니다.

class Student {
  private String studentName;
  private int regNo;
  private Double gpa;
  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
  // overriding the toString() method
  @Override
  public String toString() {
    return this.studentName + " " + this.regNo + " " + this.gpa;
  }
}

이제 이 클래스의 개체를 인쇄할 때 학생의 이름, 등록 번호 및 GPA를 볼 수 있습니다.

public class Demo {
  public static void main(String[] args) {
    Student s1 = new Student("Justin", 101, 8.81);
    System.out.print(s1);
  }
}

출력:

Justin 101 8.81

배열 객체 인쇄

배열에 있는 요소를 보려면 Arrays.toString() 메서드를 사용해야 합니다. 사용자 정의 클래스 객체의 배열이 있는 경우 사용자 정의 클래스에도 재정의된 toString() 메서드가 있어야 합니다. 이렇게 하면 클래스 속성이 올바르게 인쇄됩니다.

import java.util.Arrays;
class Student {
  private String studentName;
  private int regNo;
  private Double gpa;
  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
  // overriding the toString() method
  @Override
  public String toString() {
    return this.studentName + " " + this.regNo + " " + this.gpa;
  }
}
public class Demo {
  public static void main(String[] args) {
    Student s1 = new Student("Justin", 101, 8.81);
    Student s2 = new Student("Jessica", 102, 9.11);
    Student s3 = new Student("Simon", 103, 7.02);

    // Creating Arrays
    Student[] studentArr = {s1, s2, s3};
    int[] intArr = {5, 10, 15};
    double[] doubleArr = {5.0, 10.0, 15.0};
    String[] stringArr = {"Justin", "Jessica"};

    System.out.println("Student Array: " + Arrays.toString(studentArr));
    System.out.println("Intger Array: " + Arrays.toString(intArr));
    System.out.println("Double Array: " + Arrays.toString(doubleArr));
    System.out.println("String Array: " + Arrays.toString(stringArr));
  }
}

출력:

Student Array: [Justin 101 8.81, Jessica 102 9.11, Simon 103 7.02]
Intger Array: [5, 10, 15]
Double Array: [5.0, 10.0, 15.0]
String Array: [Justin, Jessica]

다차원 배열 객체 인쇄

다차원 배열의 경우 toString() 메서드 대신 deepToString() 메서드를 사용하고 원하는 출력을 콘솔에 가져옵니다.

import java.util.Arrays;
class Student {
  private String studentName;
  private int regNo;
  private Double gpa;

  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
  // overriding the toString() method
  @Override
  public String toString() {
    return this.studentName + " " + this.regNo + " " + this.gpa;
  }
}
public class Demo {
  public static void main(String[] args) {
    Student s1 = new Student("Justin", 101, 8.81);
    Student s2 = new Student("Jessica", 102, 9.11);
    Student s3 = new Student("Simon", 103, 7.02);
    Student s4 = new Student("Harry", 104, 8.0);
    Student[][] twoDimStudentArr = {{s1, s2}, {s3, s4}};
    System.out.println("Using toString(): " + Arrays.toString(twoDimStudentArr));
    System.out.println("Using deepToString(): " + Arrays.deepToString(twoDimStudentArr));
  }
}

출력:

Using toString(): [[LStudent;@7a81197d, [LStudent;@5ca881b5]
Using deepToString(): [[Justin 101 8.81, Jessica 102 9.11], [Simon 103 7.02, Harry 104 8.0]]

Java에서 컬렉션 개체 인쇄

Lists, SetsMaps와 같은 컬렉션에는 Arrays.toString()과 같은 추가 메서드가 필요하지 않습니다. 클래스의 toString() 메서드를 적절하게 재정의했다면 컬렉션을 인쇄하기만 하면 원하는 출력을 얻을 수 있습니다.

import java.util.ArrayList;
import java.util.HashSet;
class Student {
  private String studentName;
  private int regNo;
  private Double gpa;
  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
  // overriding the toString() method
  @Override
  public String toString() {
    return this.studentName + " " + this.regNo + " " + this.gpa;
  }
}
public class Demo {
  public static void main(String[] args) {
    Student s1 = new Student("Justin", 101, 8.81);
    Student s2 = new Student("Jessica", 102, 9.11);
    Student s3 = new Student("Simon", 103, 7.02);

    // Creating an ArrayList
    ArrayList<Student> studentList = new ArrayList<>();
    studentList.add(s1);
    studentList.add(s2);
    studentList.add(s3);
    // Creating a Set
    HashSet<Student> studentSet = new HashSet<>();
    studentSet.add(s1);
    studentSet.add(s2);
    studentSet.add(s3);
    System.out.println("Student List: " + studentList);
    System.out.println("Student Set: " + studentSet);
  }
}

출력:

Student List: [Justin 101 8.81, Jessica 102 9.11, Simon 103 7.02]
Student Set: [Simon 103 7.02, Justin 101 8.81, Jessica 102 9.11]

Apache Commons 라이브러리 사용

Apache Commons 라이브러리로 작업하는 경우 Apache Commons 라이브러리의 ToStringBuilder 클래스를 사용하여 다른 방식으로 객체의 형식을 지정합니다. 이 클래스의 reflectionToString() 메서드를 사용할 수 있습니다.

이 메서드를 사용하여 속성에 대해 설정된 개체 클래스와 해시 코드 및 값을 간단히 인쇄할 수 있습니다.

import org.apache.commons.lang3.builder.ToStringBuilder;
class Student {
  private String studentName;
  private int regNo;
  private Double gpa;
  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this);
  }
}
public class Demo {
  public static void main(String[] args) {
    Student s = new Student("Justin", 101, 8.81);
    System.out.print(s);
  }
}

출력:

Student@25f38edc[gpa=8.81,regNo=101,studentName=Justin]

해시 코드를 생략하려면 SHORT_PREFIX_STYLE 상수를 사용할 수 있습니다. 아래 예를 참조하십시오.

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

class Student {
  private String studentName;
  private int regNo;
  private Double gpa;

  Student(String s, int i, Double d) {
    this.studentName = s;
    this.regNo = i;
    this.gpa = d;
  }
  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
  }
}
public class Demo {
  public static void main(String[] args) {
    Student s = new Student("Justin", 101, 8.81);
    System.out.print(s);
  }
}

출력:

Student[gpa=8.81,regNo=101,studentName=Justin]

클래스에 중첩된 개체가 포함된 경우 RecursiveToStringStyle() 메서드를 사용하여 개체를 인쇄할 수 있습니다.

@Override
public String toString() {
  return ToStringBuilder.reflectionToString(this, new RecursiveToStringStyle());
}

요약

Object 클래스는 Java의 모든 클래스의 상위 클래스입니다. 객체를 출력할 때 호출되는 toString() 메소드는 Object 클래스에서 구현됩니다. 그러나 이 구현은 사용자 정의 클래스 속성에 대한 정보를 제공하지 않습니다. 이러한 속성을 제대로 보려면 클래스의 toString() 메서드를 재정의해야 합니다. 배열의 경우 toString() 메서드 또는 deepToString()을 직접 사용할 수 있습니다.

관련 문장 - Java Object