[자바] Class 클래스란?

스프링 프레임워크에 대해 공부를 하던 중 .class 와 .getClass() 라는 키워드, 함수를 마주치게 되었다. 자바에서는 primitive type 을 제외한 모든 것이 객체라는 것, 모든 클래스는 슈퍼 클래스로 Object를 상속한다는 것은 알고 있었는데 이것 외에도 class클래스라는 것이 있다고 해서 이에 대해 더 자세히 알고 싶어졌다.

  • Q) What does .class mean in Java? For example, if I created a class called Print. What does Print.class return?

  • A) When you write .class after a class name, it references the class literal - java.lang.Class object that represents information about given class. For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.

Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName()); 
//밑에 두 줄의 코드는 같은 결과를 출력한다고 한다  
  • class 클래스
    • 클래스와 인스턴스의 메타 데이터를 얻을 수 있다(=리플렉션)
      • 메타 데이터 : 클래스이름, 생성자, 필드, 메서드 정보
    • 객체로부터 얻는법, 클래스 이름으로부터 얻는 법(패키지명.class)
  • 객체로부터 얻는 법
Student student1 = new Student();
Class clazz = student1.getClass();
Field[] field = clazz.getDeclaredFields();
for(Field field1 : field){
    System.out.println("필드 = " + field1);
}
  • 클래스 이름으로부터 얻는 법
Class clazz2 = Class.forName("practice622.Student");
Field[] field = clazz2.getDeclaredFields();
for(Field field1 : field){
    System.out.println("필드 = " + field1);
}
  • 결론 : Student.class 는 student1.getClass() 메서드에 의해 반환되는 객체와 동일한 객체이다

좋은 웹페이지 즐겨찾기