什么是 Class 对象(java.lang.Class)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4453349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:44:41  来源:igfitidea点击:

what is the Class object (java.lang.Class)?

javaclassinheritance

提问by Carbonizer

The Java documentation for Classsays:

的 Java 文档Class说:

Classobjects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClassmethod in the class loader.

ClassJava 虚拟机在加载类时以及通过调用defineClass类加载器中的方法自动构造对象。

What are these Classobjects? Are they the same as objects instantiated from a class by calling new?

这些Class对象是什么?它们与通过调用从类实例化的对象相同new吗?

Also, for example object.getClass().getName()how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?

另外,例如,即使我没有继承自,object.getClass().getName()如何将所有内容都类型转换为 superclass ?Classjava.lang.Class

采纳答案by Bozho

Nothing gets typecasted to Class. Every Objectin Java belongs to a certain class. That's why the Objectclass, which is inherited by all other classes, defines the getClass()method.

没有任何东西被类型转换为Class. ObjectJava 中的每个都属于某个class. 这就是为什么Object由所有其他类继承的类定义getClass()方法的原因。

getClass(), or the class-literal - Foo.classreturn a Classobject, which contains some metadata about the class:

getClass(),或类字面量 -Foo.class返回一个Class对象,其中包含有关该类的一些元数据:

  • name
  • package
  • methods
  • fields
  • constructors
  • annotations
  • 姓名
  • 包裹
  • 方法
  • 领域
  • 构造函数
  • 注释

and some useful methods like casting and various checks (isAbstract(), isPrimitive(), etc). the javadocshows exactly what information you can obtain about a class.

和一些有用的方法等铸造和各种检查(isAbstract()isPrimitive()等)。javadoc准确地显示了您可以获得关于类的哪些信息。

So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the @Processableannotation, then:

因此,例如,如果您的方法被赋予一个对象,并且您想处理它以防它被注释@Processable注释,那么:

public void process(Object obj) {
    if (obj.getClass().isAnnotationPresent(Processable.class)) {
       // process somehow; 
    }
}

In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Classinstance are called "reflective operations", or simply "reflection. Read hereabout reflection, why and when it is used.

在此示例中,您获取有关给定对象的类的元数据(无论它是什么),并检查它是否具有给定的注释。Class实例上的许多方法都称为“反射操作”,或简称为“反射”。在此处阅读有关反射、使用原因和使用时间的信息。

Note also that Classobject represents enums and intefaces along with classes in a running Java application, and have the respective metadata.

另请注意,Class对象表示正在运行的 Java 应用程序中的枚举和接口以及类,并具有相应的元数据。

To summarize - each object in java has (belongs to) a class, and has a respective Classobject, which contains metadata about it, that is accessible at runtime.

总而言之 - java 中的每个对象都有(属于)一个类,并且有一个相应的Class对象,其中包含有关它的元数据,可以在运行时访问。

回答by ColinD

getClass()is a method that returnsan object that is an instance of java.lang.Class... there is no casting involved. Casting would look like this:

getClass()是一种返回对象的方法,该对象是...的实例,java.lang.Class不涉及强制转换。铸造看起来像这样:

Class<?> type = (Class<?>) object;

回答by Jan Thom?

A Class object is sort of a meta object describing the class of an object. It is used mostly with the reflection capabilities of Java. You can think of it like a "blueprint" of the actual class. E.g. you have a class Car like this:

Class 对象是一种描述对象类的元对象。它主要与 Java 的反射功能一起使用。您可以将其视为实际类的“蓝图”。例如,你有一个像这样的类 Car:

public class Car {
    public String brand;
}

You can then construct a Class object which describes your "Car" class.

然后,您可以构造一个 Class 对象来描述您的“Car”类。

Class myCarClass = Class.forName("Car");

Now you can do all sorts of querying on your Car class on that Class object:

现在,您可以对该 Class 对象上的 Car 类进行各种查询:

myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field

and so on. Every java object has a method getClass() which returns the Class object describing the Class of the Java object. So you could do something like:

等等。每个 java 对象都有一个 getClass() 方法,它返回描述 Java 对象的 Class 的 Class 对象。所以你可以这样做:

Car myCar = new Car();
Class myCarClass  = myCar.getClass();

This also works for objects you don't know, e.g objects you get from the outside:

这也适用于您不知道的对象,例如您从外部获得的对象:

public void tellMeWhatThisObjectsClassIs(Object obj) {
    System.out.println(obj.getClass().getName());
}

You could feed this method any java object and it will print the actual class of the object you have given to it.

您可以将此方法提供给任何 java 对象,它会打印您提供给它的对象的实际类。

When working with Java, most of the time you don't need to worry about Class objects. They have some handy use cases though. E.g. they allow you to programmatically instanciate objects of a certain class, which is used often for object serialization and deserialization (e.g. converting Java Objects back and forth to/from XML or JSON).

在使用 Java 时,大多数时候您不需要担心 Class 对象。不过,他们有一些方便的用例。例如,它们允许您以编程方式实例化某个类的对象,这通常用于对象序列化和反序列化(例如,在 XML 或 JSON 之间来回转换 Java 对象)。

Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance();  // is roughly equivalent to = new Car();

You could also use it to find out all declared fields or methods of your class etc, which is very useful in certain cases. So e.g. if your method gets handed an unknown object and you need to know more about it, like if it imlements some interface etc, the Class class is your friend here.

您还可以使用它来查找类的所有声明字段或方法等,这在某些情况下非常有用。因此,例如,如果您的方法得到一个未知对象并且您需要了解更多关于它的信息,例如它是否实现了某些接口等,那么 Class 类就是您的朋友。

So long story short, the Class, Field, Method, etc. classes which are in the java.lang.reflect package allow you to analyze your defined classes, methods, fields, create new instances of them, call methods all kinds of other stuff and they allow you to do this dynamically at runtime.

长话短说,java.lang.reflect 包中的 Class、Field、Method 等类允许您分析定义的类、方法、字段,创建它们的新实例,调用方法等各种东西它们允许您在运行时动态执行此操作。

回答by Pakka Techie

A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question

Class 对象是 Class (java.lang.Class) 的一个实例。下面从类的 javadoc 引用应该回答你的问题

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.

类没有公共构造函数。相反,Java 虚拟机在加载类时以及通过调用类加载器中的 defineClass 方法时自动构造 Class 对象。

回答by Koray Tugay

I would also like to add to ColinD 's answer that getClass will return the same objectfor instances of same type. This will print true:

我还想添加到 ColinD 的答案中,即 getClass 将为相同类型的实例返回相同的对象。这将打印true

    MyOtherClass foo = new MyOtherClass();
    MyOtherClass bar = new MyOtherClass();
    System.out.println(foo.getClass()==bar.getClass());

Note that it is not equals, I am using ==.

请注意,它不是equals,我正在使用==.

回答by Ishanka Abeysinghe

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.

Object类默认是java中所有类的父类。换句话说,它是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.

如果您想引用任何您不知道其类型的对象,则 Object 类很有用。请注意,父类引用变量可以引用子类对象,称为向上转换。

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:

让我们举个例子,有 getObject() 方法返回一个对象,但它可以是任何类型,如 Employee、Student 等,我们可以使用 Object 类引用来引用该对象。例如:

Object obj=getObject();//we don't know what object will be returned from this method

Object obj=getObject();//我们不知道这个方法会返回什么对象

回答by Brendon Cheung

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 .javafile you create, when you compile that .javafile, the jvm will creates a .classfile, this file contains all the information about the class, namely:

为了完全理解类对象,让我们回过头来理解我们首先得到了类对象。你看,.java你创建的每一个文件,当你编译那个.java文件时,jvm 都会创建一个.class文件,这个文件包含关于这个类的所有信息,即:

  1. Fully qualified name of the class
  2. Parent of class
  3. Method information
  4. Variable fields
  5. Constructor
  6. Modifier information
  7. Constant pool
  1. 类的全限定名
  2. 班级家长
  3. 方法信息
  4. 变量字段
  5. 构造函数
  6. 修饰符信息
  7. 常量池

The list you see above is what you typically see in a typical class. Now, up to this point, your .javafile and .classfile 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 .classfile in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .classfile into the method area, the jvm will use that information and a Class object that representsthat class that exists in the heap memory area.

您在上面看到的列表是您在典型课程中通常看到的列表。现在,到目前为止,您的.java文件和.class文件都存在于您的硬盘上,当您实际需要使用该类即在main()方法中执行代码时,jvm 将使用.class您硬盘中的该文件并将其加载到 5 个内存之一中在 jvm 中的区域,也就是方法区,在将.class文件加载到方法区后,jvm 将立即使用该信息和一个 Class 对象,该对象表示存在于堆内存区中的该类。

Here is the top level view,

这是顶层视图,

.java--compile--> .class-->when you execute your script--> .classloads into method area --jvm creates class object from method area--> a class object is born

.java--compile--> .class-->当你执行你的脚本时-->.class加载到方法区--jvm从方法区创建类对象-->一个类对象诞生了

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

希望这是有道理的