简体   繁体   English

.class 在 Java 中是什么意思?

[英]What does .class mean in Java?

What does .class mean in Java? .class在 Java 中是什么意思? For example, if I created a class called Print .例如,如果我创建了一个名为Print的类。 What does Print.class return? Print.class返回什么?

When you write .class after a class name, it references the class literal - java.lang.Class object that represents information about given class.当您在类名后写入.class ,它引用类文字 - java.lang.Class对象,该对象表示有关给定类的信息。

For example, if your class is Print , then Print.class is an object that represents the class Print on runtime.例如,如果您的类是Print ,则Print.class是一个表示运行时类Print的对象。 It is the same object that is returned by the getClass() method of any (direct) instance of Print .它与Print的任何(直接)实例的getClass()方法返回的对象相同。

Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());

.class is used when there isn't an instance of the class available. .class在没有可用的类实例时使用。

.getClass() is used when there is an instance of the class available. .getClass()在有可用类的实例时使用。

object.getClass() returns the class of the given object. object.getClass()返回给定对象的类。

For example:例如:

String string = "hello";
System.out.println(string.getClass().toString());

This will output:这将输出:

class java.lang.String

This is the class of the string object :)这是字符串对象的类:)

Just to clarify, this '.class' method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.澄清一下,这个“.class”方法不是指你在编译java代码后看到的字节码文件,也不是OOP理论中类与对象概念之间的混淆。

This '.class' method is used in Java for code Reflection.这个'.class'方法在Java中用于代码反射。 Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.通常,您可以为您的类收集元数据,例如完全限定的类名、常量列表、公共字段列表等。

Check these links (already mentioned above) to get all the details:检查这些链接(上面已经提到)以获取所有详细信息:
https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

Normally you don't plan on using Reflection right away when you start building your project.通常,当您开始构建项目时,您不打算立即使用反射。 It's something that you know you need after trying to manage already working code.在尝试管理已经可以工作的代码后,您知道您需要它。 Many times you need it to manage multiple instances of your program.很多时候你需要它来管理你的程序的多个实例。 Maybe you want to identify each particular 'clone' to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.也许您想识别每个特定的“克隆”以确定是否已经定义了某些东西,或者计算函数的数量,或者只是简单地记录类的特定实例的详细信息。

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()如果一个对象的实例可用,那么获取它的 Class 的最简单方法是调用Object.getClass()

The .class Syntax .class语法

If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type.如果类型可用但没有实例,则可以通过将.class附加到类型名称来获取类。 This is also the easiest way to obtain the Class for a primitive type.这也是获取原始类型的 Class 的最简单方法。

boolean b;
Class c = b.getClass();   // compile-time error

Class c = boolean.class;  // correct

See: docs.oracle.com about class请参阅: docs.oracle.com 关于类

If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object.如果没有可用的实例,则使用.class语法获取类的相应 Class 对象,否则您可以使用 getClass() 方法获取 Class 对象。 Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.由于没有原始数据类型的实例,我们必须对原始数据类型使用.class语法。

    package test;

    public class Test {
       public static void main(String[] args)
       {
          //there is no instance available for class Test, so use Test.class
          System.out.println("Test.class.getName() ::: " + Test.class.getName());

          // Now create an instance of class Test use getClass()
          Test testObj = new Test();
          System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());

          //For primitive type
          System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
          System.out.println("int.class.getName() ::: " + int.class.getName());
          System.out.println("char.class.getName() ::: " + char.class.getName());
          System.out.println("long.class.getName() ::: " + long.class.getName());
       }
    }

I think the key here is understanding the difference between a Class and an Object.我认为这里的关键是理解类和对象之间的区别。 An Object is an instance of a Class.一个对象是一个类的实例。 But in a fully object-oriented language, a Class is also an Object .但是在完全面向对象的语言中, Class 也是一个 Object So calling .class gets the reference to the Class object of that Class, which can then be manipulated.因此调用.class会获得对该类的 Class 对象的引用,然后可以对其进行操作。

A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.'类字面量是一个表达式,由类、接口、数组或原始类型的名称或伪类型 void 组成,后跟一个“.”。 and the token class.和令牌类。 One of the changes in JDK 5.0 is that the class java.lang.Class is generic, java.lang.Class Class<T> , therefore: JDK 5.0 中的变化之一是类 java.lang.Class 是泛型的java.lang.Class Class<T> ,因此:

Class<Print> p = Print.class;

References here:参考这里:

https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

http://docs.oracle.com/javase/tutorial/extra/generics/literals.html http://docs.oracle.com/javase/tutorial/extra/generics/literals.html

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2 http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2

Adding to the above answers:补充上面的答案:

Suppose you have aa class named "myPackage.MyClass".假设您有一个名为“myPackage.MyClass”的类。 Assuming that is in classpath, the following statements are equivalent.假设它在类路径中,以下语句是等效的。

//checking class name using string comparison, only Runtime check possible
if(myInstance.getClass().getName().equals(Class.forName("myPackage.MyClass")).getName()){}

//checking actual Class object for equality, only Runtime check possible
if(myInstance.getClass().getName() == Class.forName("myPackage.MyClass"))){}

//checking actual Class object for equality, but compile time validation
//will ensure MyClass is in classpath. Hence this approach is better (according to fail-fast paradigm)
if(myInstance.getClass() == MyClass.class){}

Similarly, the following are also equivalent.类似地,以下也是等价的。

Class<?> myClassObject = MyClass.class; //compile time check

Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check

If JVM loads a type, a class object representing that type will be present in JVM.如果 JVM 加载一个类型,则表示该类型的类对象将出现在 JVM 中。 we can get the metadata regarding the type from that class object which is used very much in reflection package.我们可以从反射包中经常使用的类对象中获取有关类型的元数据。 MyClass.class is a shorthand method which actually points to the Class object representing MyClass. MyClass.class 是一种速记方法,它实际上指向代表 MyClass 的 Class 对象。

As an addendum, some information about Class<?> reference which will be useful to read along with this as most of the time, they are used together.作为附录,一些关于 Class<?> 参考的信息将有助于阅读,因为大多数情况下,它们是一起使用的。

Class<?> reference type can hold any Class object which represents any type. Class<?> 引用类型可以包含代表任何类型的任何 Class 对象。

This works in a similar fashion if the Class<?> reference is in method argument as well.如果 Class<?> 引用也在方法参数中,这将以类似的方式工作。

Please note that the class "Class" does not have a public constructor.请注意,“Class”类没有公共构造函数。 So you cannot instantiate "Class" instances with "new" operator.所以你不能用“new”运算符实例化“Class”实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM