Skip to Content
Suffering builds character

3.Class 클래스

1. Class 클래스

Instances of the class Class represent classes and interfaces in a running Java application.

자바의 모든 클래스는 해당 클래스 자체의 구성 정보를 담은 Class 타입의 오브젝트를 반환하는 메서드를 Java의 최상위 클래스인 Object를 통해 상속받고 있음

Object.java
public class Object { // Constructs a new object. public Object() {} /** * Returns the runtime class of this {@code Object}. The returned * {@code Class} object is the object that is locked by {@code * static synchronized} methods of the represented class. * * <p><b>The actual result type is {@code Class<? extends |X|>} * where {@code |X|} is the erasure of the static type of the * expression on which {@code getClass} is called.</b> For * example, no cast is required in this code fragment:</p> * * <p> * {@code Number n = 0; }<br> * {@code Class<? extends Number> c = n.getClass(); } * </p> * * @return The {@code Class} object that represents the runtime * class of this object. * @jls 15.8.2 Class Literals */ @HotSpotIntrinsicCandidate public final native Class<?> getClass(); // 그 외 다른 코드.. }

이러한 Class 타입의 객체를 이용하면 해당 클래스 코드에 대한 메타 정보를 조회하거나 오브젝트를 조작할 수 있음

  • 클래스의 이름이 무엇인지
  • 어떤 클래스를 상속하고 있는지
  • 어떤 인터페이스를 구현했는지
  • 어떤 필드를 가지고 있고
  • 각각의 타입은 무엇인지
  • 메서드는 어떤 것을 정의했고
  • 메서드의 파라미터와 리턴 타입은 무엇인지 등
Main.java
public class Main { public static void main(String[] args) { // String 클래스의 인스턴스 생성 String str = "Hello"; // getClass() 메서드를 사용하여 Class 객체 얻기 Class<?> stringClass = str.getClass(); Person person = new Person(); Class<? extends Person> personClass = person.getClass(); // Class 객체의 이름을 조회하는 메서드를 통해 결과값 확인 System.out.println("String 타입의 Class 이름 = " + stringClass.getName()); System.out.println("Person 타입의 Class 이름 = " + personClass.getName()); } } class Person { // ... }

실행 결과

Console
String 타입의 Class 이름 = java.lang.String Person 타입의 Class 이름 = dev.spring.core.Person

그 외에도 추가적으로 특정 객체의 필드가 가진 값을 읽거나 수정할 수도 있고, 원하는 파라미터 값을 이용해 해당 객체가 가진 메서드를 호출할 수도 있음

Last updated on