java .class 在类名后面是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15101794/
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-10-31 18:28:53  来源:igfitidea点击:

What does .class mean after a class name

java

提问by user2055603

What does .classmean in, for example, MyClass.class? I understand that when you put the name of a class and the point it is used to access its static fields or methods, but that doesn't relate to '.class'

是什么.class意思,例如,MyClass.class?我知道当您输入类的名称以及它用于访问其静态字段或方法的点时,但这与“.class”无关

回答by Andrew Mao

SomeClass.classgets the Class<SomeClass>type which you can use for programming using the reflection API.

SomeClass.class获取Class<SomeClass>可用于使用反射 API进行编程的类型。

You can get the same type if you have an instance of the class using instance.getClass().

如果您有使用 的类的实例,则可以获得相同的类型instance.getClass()

You can check out the documentation here. For example, you can:

您可以在此处查看文档。例如,您可以:

  • get the names of fields and methods, annotations, etc.
  • invoke methods, get constructor to create new instances of the class
  • get the name of the class, the superclass, package, etc
  • 获取字段和方法的名称、注释等。
  • 调用方法,获取构造函数以创建类的新实例
  • 获取类名、超类名、包名等

回答by Javier

When you write .classafter a class name, it references the Classobject that represents the given class (formally, it is a named class literal). The the type of NombreClase.classis Class<NombreClase>.

当你写.class在一个类名之后时,它引用了Class代表给定类的对象(正式地,它是一个命名的类文字)。的类型NombreClase.classClass<NombreClase>

E.g., NombreClase.classis an object that represents the class NombreClaseon runtime. It is the same object that is returned by the getClass()method of any (direct) instance of NombreClase.

例如,NombreClase.class是一个表示NombreClase运行时类的对象。它与getClass()的任何(直接)实例的方法返回的对象相同NombreClase

NombreClase obj = new NombreClase();
System.out.println(NombreClase.class.getName());
System.out.println(obj.getClass().getName())

回答by jahroy

You can add .classto the name of any class to retrieve an instance of its Classobject.

您可以添加.class到任何类的名称以检索其Class对象的实例。

When you use Integer.classyou reference an instance of Class<Integer>, which is a typed class object.

当您使用时,Integer.class您会引用 的一个实例Class<Integer>,它是一个类型化的类对象。

I always thought this was a field member that got added by the compiler, but it looks like it's really just syntactic sugar.

我一直认为这是编译器添加的字段成员,但看起来它实际上只是语法糖。