자바 typeof 연산자

Mohammad Irfan 2023년10월12일
  1. Java에서 변수/값 유형 가져오기
  2. Java에서 모든 변수/값의 유형 가져오기
자바 typeof 연산자

이 자습서에서는 Java에서 변수 또는 값의 데이터 유형을 가져오는 방법을 소개하고 주제를 이해하기 위한 몇 가지 예제 코드를 나열합니다.

Java에서 변수의 유형이나 값을 가져오기 위해 Object 클래스의 getClass() 메서드를 사용할 수 있습니다. 유형을 확인하기 위해 typeof() 메소드를 사용하는 JavaScript와 달리 이것은 이를 수행하는 유일한 방법입니다.

Object 클래스의 getClass() 메소드를 사용했기 때문에 프리미티브가 아닌 객체에서만 작동합니다. 프리미티브 유형을 얻으려면 먼저 래퍼 클래스를 사용하여 변환하십시오. 몇 가지 예를 들어 이해합시다.

Java에서 변수/값 유형 가져오기

이 예제에서는 getClass()를 사용하여 변수 유형을 확인했습니다. 이 변수는 문자열 유형이므로 메서드를 직접 호출할 수 있습니다. 아래 예를 참조하십시오.

getClass() 메소드는 우리의 경우 java.lang.String과 같은 패키지 이름을 포함하여 완전한 클래스 이름을 반환합니다.

public class SimpleTesting {
  public static void main(String[] args) {
    String msg = "Hello";
    System.out.println(msg);
    System.out.println("Type is: " + msg.getClass());
  }
}

출력:

Hello
Type is: class java.lang.String

Java에서 모든 변수/값의 유형 가져오기

위의 예에서 우리는 문자열 변수를 사용했고 유사하게 유형을 얻었습니다. 다른 유형의 변수를 사용할 수도 있으며 이 메서드는 원하는 결과를 반환합니다. 아래 예를 참조하십시오.

이 예제에서는 string 외에 정수와 문자라는 두 개의 변수를 더 만들고 getClass() 메서드를 사용했습니다.

package javaexample;
public class SimpleTesting {
  public static void main(String[] args) {
    String msg = "Hello";
    System.out.println(msg);
    System.out.println("Type is: " + msg.getClass());
    // Integer
    Integer val = 20;
    System.out.println(val);
    System.out.println("Type is: " + val.getClass());
    // Character
    Character ch = 'G';
    System.out.println(ch);
    System.out.println("Type is: " + ch.getClass());
  }
}

출력:

Hello
Type is: class java.lang.String
20
Type is: class java.lang.Integer
G
Type is: class java.lang.Character

getClass() 메서드는 패키지 이름을 포함하여 클래스의 완전한 정규화된 이름을 반환합니다. 유형 이름만 가져오려면 단일 문자열을 반환하는 getSimpleName() 메서드를 사용할 수 있습니다. 아래 예를 참조하십시오.

package javaexample;
public class SimpleTesting {
  public static void main(String[] args) {
    String msg = "Hello";
    System.out.println(msg);
    System.out.println("Type is: " + msg.getClass().getSimpleName());

    // Integer
    Integer val = 20;
    System.out.println(val);
    System.out.println("Type is: " + val.getClass().getSimpleName());

    // Character
    Character ch = 'G';
    System.out.println(ch);
    System.out.println("Type is: " + ch.getClass().getSimpleName());
  }
}

출력:

Hello
Type is: String
20
Type is: Integer
G
Type is: Character

관련 문장 - Java Operator