Class 객체 (java.lang.Class)는 무엇입니까?
에 대한 Java 문서 Class
는 다음 과 같이 말합니다.
Class
객체는 클래스가로드 될 때 Java Virtual Machine에 의해 그리고defineClass
클래스 로더 의 메소드에 대한 호출에 의해 자동으로 구성됩니다 .
이 Class
물건 들은 무엇입니까 ? 호출하여 클래스에서 인스턴스화 된 객체와 동일 new
합니까?
또한 예를 들어 내가 상속하지 않더라도 object.getClass().getName()
어떻게 모든 것을 superclass로 형변환 할 수 있습니까?Class
java.lang.Class
아무것도 형변환되지 않습니다 Class
. Object
Java의 모든 것은 특정 class
. 이것이 Object
다른 모든 클래스에 상속 된 클래스가 getClass()
메서드를 정의하는 이유 입니다.
getClass()
또는 class-literal- 클래스에 대한 일부 메타 데이터를 포함 Foo.class
하는 Class
객체를 반환합니다 .
- 이름
- 꾸러미
- 행동 양식
- 필드
- 생성자
- 주석
주조 및 각종 검사와 같은 몇 가지 유용한 방법 ( isAbstract()
, isPrimitive()
, 등). javadoc 은 클래스에 대해 얻을 수있는 정보를 정확히 보여줍니다.
예를 들어, 당신의 메서드에 객체가 주어지고 주석으로 @Processable
주석 이 달린 경우 처리하려면 다음을 수행하십시오.
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
이 예에서는 주어진 객체의 클래스에 대한 메타 데이터를 얻고 (무엇이든) 주어진 주석이 있는지 확인합니다. Class
인스턴스 에 대한 많은 메서드를 "반사 연산"또는 간단히 "반사"라고합니다. 여기에서 리플렉션이 사용되는 이유와시기에 대해 읽어보십시오 .
또한 Class
object는 실행중인 Java 애플리케이션의 클래스와 함께 열거 형 및 인터페이스를 나타내며 각각의 메타 데이터를 가지고 있습니다.
요약하자면 자바의 각 객체는 클래스에 속하며 Class
런타임에 액세스 할 수 있는 해당 객체에 대한 메타 데이터를 포함하고 있습니다.
Class 객체는 객체의 클래스를 설명하는 일종의 메타 객체입니다. 주로 Java의 리플렉션 기능과 함께 사용됩니다. 실제 클래스의 "청사진"이라고 생각할 수 있습니다. 예를 들어 다음과 같은 클래스 Car가 있습니다.
public class Car {
public String brand;
}
그런 다음 "Car"클래스를 설명하는 Class 객체를 생성 할 수 있습니다.
Class myCarClass = Class.forName("Car");
이제 해당 Class 객체의 Car 클래스에 대해 모든 종류의 쿼리를 수행 할 수 있습니다.
myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field
등등. 모든 Java 객체에는 Java 객체의 클래스를 설명하는 Class 객체를 반환하는 getClass () 메소드가 있습니다. 따라서 다음과 같이 할 수 있습니다.
Car myCar = new Car();
Class myCarClass = myCar.getClass();
이것은 또한 당신이 모르는 개체, 예를 들어 외부에서 얻은 개체에 대해서도 작동합니다.
public void tellMeWhatThisObjectsClassIs(Object obj) {
System.out.println(obj.getClass().getName());
}
이 메소드에 자바 객체를 공급할 수 있으며 주어진 객체의 실제 클래스를 인쇄합니다.
Java로 작업 할 때 대부분의 경우 Class 객체에 대해 걱정할 필요가 없습니다. 하지만 몇 가지 편리한 사용 사례가 있습니다. 예를 들어 객체 직렬화 및 역 직렬화에 자주 사용되는 특정 클래스의 객체를 프로그래밍 방식으로 인스턴스화 할 수 있습니다 (예 : Java 객체를 XML 또는 JSON으로 / 뒤로 변환).
Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance(); // is roughly equivalent to = new Car();
특정 경우에 매우 유용한 클래스 등의 선언 된 모든 필드 또는 메서드를 찾는 데 사용할 수도 있습니다. 예를 들어 메서드가 알려지지 않은 객체를 전달 받고 이에 대해 더 많이 알아야하는 경우 (예 : 일부 인터페이스를 구현하는 경우) Class 클래스가 여기에서 친구가됩니다.
간단히 말해서 java.lang.reflect 패키지에있는 Class, Field, Method 등의 클래스를 사용하면 정의 된 클래스, 메소드, 필드를 분석하고, 새로운 인스턴스를 생성하고, 모든 종류의 메소드를 호출 할 수 있습니다. 런타임에이를 동적으로 수행 할 수 있습니다.
getClass()
... 의 인스턴스 인 객체 를 반환 하는 메서드입니다 java.lang.Class
. 캐스팅이 필요하지 않습니다. 캐스팅은 다음과 같습니다.
Class<?> type = (Class<?>) object;
또한 getClass가 동일한 유형의 인스턴스에 대해 동일한 객체 를 반환한다는 ColinD의 답변에 추가하고 싶습니다 . 이것은 true 를 인쇄 합니다 .
MyOtherClass foo = new MyOtherClass();
MyOtherClass bar = new MyOtherClass();
System.out.println(foo.getClass()==bar.getClass());
가되지 않도록주의 동일 , 내가 사용하고 == .
A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject()
;//we don't know what object will be returned from this method
In order to fully understand the class object, let go back in and understand we get the class object in the first place. You see, every .java
file you create, when you compile that .java
file, the jvm will creates a .class
file, this file contains all the information about the class, namely:
- Fully qualified name of the class
- Parent of class
- Method information
- Variable fields
- Constructor
- Modifier information
- Constant pool
The list you see above is what you typically see in a typical class. Now, up to this point, your .java
file and .class
file exists on your hard-disk, when you actually need to use the class i.e. executing code in main()
method, the jvm will use that .class
file in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .class
file into the method area, the jvm will use that information and a Class object that represents that class that exists in the heap memory area.
Here is the top level view,
.java
--compile--> .class
-->when you execute your script--> .class
loads into method area --jvm creates class object from method area--> a class object is born
With a class object, you are obtain information such as class name, and method names, everything about the class.
Also to keep in mind, there shall only be one class object for every class you use in the script.
Hope this makes sense
참고URL : https://stackoverflow.com/questions/4453349/what-is-the-class-object-java-lang-class
'code' 카테고리의 다른 글
좋은 경량 Python MVC 프레임 워크는 무엇입니까? (0) | 2020.10.29 |
---|---|
jQuery 이벤트 .load (), .ready (), .unload () (0) | 2020.10.29 |
문자열이 너무 긴 경우“…”로 어떻게자를 수 있습니까? (0) | 2020.10.29 |
Android에서 아랍어 텍스트를 지원하는 방법은 무엇입니까? (0) | 2020.10.29 |
새 페이지로 리디렉션하는 aspx 페이지 (0) | 2020.10.28 |