有人可以解释一下 java 中的 .getClass() 方法吗

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

Could someone explain me the .getClass() method in java

javaobjectmethodstypesreturn

提问by John

I am currently taking a java class in university. This is my first programming class and I've stumbled on something that I just cannot understand. As i learned, there are two ways of comparing variables. The first is using the ==, !=, <, >, =<, >=signs for PRIMITIVE variables such as int,double,etc. and the second way is to use the .equals() method for reference type. Now here is my question:

我目前正在大学上一门java课程。这是我的第一堂编程课,我偶然发现了一些我无法理解的东西。据我所知,有两种比较变量的方法。第一种是使用==, !=, <, >, =<,>=符号表示 PRIMITIVE 变量,例如 int、double 等。第二种方法是使用 .equals() 方法作为引用类型。现在这是我的问题:

When I use the .getClass()method, I can compare two classes with the .equals() method and the ==/ !=method. Since I can use the ==/!=signs, I'd suppose that the .getClass()method which returns the class of an object must return a primitive type. But searching on google the only thing I found out about this method in the java API is that it returns the class of an object. It doesn't tell me the variable type it returns. How exactly does this method work. What does it return? I tried to ask my teacher but she didn't know. Thank you!

当我使用该.getClass()方法时,我可以使用 .equals() 方法和==/!=方法比较两个类。由于我可以使用==/!=符号,因此我认为.getClass()返回对象类的方法必须返回原始类型。但是在 google 上搜索,我在 java API 中发现的关于此方法的唯一一件事是它返回对象的类。它没有告诉我它返回的变量类型。这种方法究竟是如何工作的。它返回什么?我试着问我的老师,但她不知道。谢谢!

采纳答案by Sweeper

You first need to know how ==and !=compare the two operands. The reason why ==and !=cannot be used to compare reference types is that they actually compare the memory addressesof the two reference type variables.

首先,您需要知道如何==!=比较两个操作数。为什么原因==!=不能用来比较引用类型是,他们实际上比较的内存地址两个引用类型变量。

So if I have two strings:

所以如果我有两个字符串:

String x = "Hello";
String y = x;

Since xand yshare the same memory address after the second line is executed, x == yevaluates to true.

由于xy被执行后的第二线,共享相同的存储器地址x == y计算为True。

The same goes for the getClass()method. The getClass()method returns the class of the object as a Class<T>object. The question is, why this evaluates to true:

这同样适用于该getClass()方法。该getClass()方法将对象的类作为Class<T>对象返回。问题是,为什么这评估为真:

x.getClass() == y.getClass()

The answer is simple. Because xand yare both of type String. So calling getClasswill return the same instance. This means the two returned the objects share the same memory address.

答案很简单。因为xy都是 类型String。所以调用getClass将返回相同的实例。这意味着两个返回的对象共享相同的内存地址。

"But when I compare strings with the same characters with the ==operator, it evaluates to false!" you shouted.

“但是当我将具有相同字符的字符串与==运算符进行比较时,它的计算结果为 false!” 你喊道。

This is because the strings are located at different memory addresses. But the classes that getClasswill return is always at the same memory address if the class that they represent is the same. This is due to the way ClassLoaderworks. But I'm not an expert that.

这是因为字符串位于不同的内存地址。但是,getClass如果它们代表的类相同,则返回的类始终位于相同的内存地址。这是由于ClassLoader工作方式。但我不是专家。

You just need to know that the objects returned by getClass is at the same memory address if the classes they represent are the same.

您只需要知道 getClass 返回的对象在它们代表的类相同的情况下位于相同的内存地址。

回答by Eran

getClass()returns an instance (object) of the Classclass. Since each Java class has a single instance of the Classclass, if two objects belong to the same class, getClass()for those two objects will return the same isntance and therefore you can use ==for comparing them, since ==when applied to reference types determines if the two references refer to the same instance.

getClass()返回类的实例(对象)Class。由于每个 Java 类都有一个类的单个实例Class,如果两个对象属于同一个类,getClass()那么这两个对象将返回相同的实例,因此您可以==用于比较它们,因为==当应用于引用类型时,确定两个引用参考同一个实例。

回答by hotzst

The comparators ==and !=compare equality in the way of identity. So how this works for primitives is obvious. However it can also be used to compare objects. However most often this does not work as expected. There are some exceptions:

比较器==!=比较器以相同的方式比较相等。所以这对基元的作用是显而易见的。但是,它也可以用于比较对象。然而,大多数情况下这不会按预期工作。有一些例外:

Strings are stored as literals, therefore if you define two instances of Stringcontaining the same value, they use the same literal. Think of this like both instances pointing to the same memory location.

Strings 存储为文字,因此如果您定义String包含相同值的两个实例,它们将使用相同的文字。把这想象成两个实例都指向同一个内存位置。

Enums are basically a collection of constants, therefore an enum value is either the same instance or it is not. It cannot be that the enum has the same value but is another instance.

Enums 基本上是常量的集合,因此枚举值要么是同一个实例,要么不是。不可能是枚举具有相同的值而是另一个实例。

The same is true for Classobjects, which is what you get when calling getClass(). A Classobject is created by the ClassLoaderthe first time it is the *.class file is loaded. On subsequent calls the same Classobject is used. Therefore Classobjects may be compared with ==and !=. However beware that if A.classis loaded by two different ClassLoaders, the class objects that you get returned from them are not of the same instance.

Class对象也是如此,这就是调用getClass(). 甲Class对象由创建ClassLoader它是在*的.class文件被加载的第一次。在后续调用中使用相同的Class对象。因此Class对象可以与==和进行比较!=。但是请注意,如果A.class由两个不同的ClassLoaders加载,则从它们返回的类对象不是同一个实例。

回答by Handox

polymorphism is one of the most important feature for java. for example:

多态是java最重要的特性之一。例如:

//this shows one use of getclass method.

public class Main {

    public static void main(String[] args) {
        Main m = new Main();
        Animal animal = new Animal();
        Human human = new Human();
        m.dosomething(animal);//print animal
        m.dosomething(human);//print human
    }

    private void dosomething(Animal an){
        System.out.println(an.getClass().toString());
        }

    }

class Human extends Animal{

    private void dance(){
        }
}

class Animal{

    private void eat(){
        }
}

回答by D.Ye

The .getClass method will just return the class of the object. When you declare a new instance of an object, it will be referring to a class. There can only be one class per jvm but multiple object referring to it. So when you get the class of two objects, they might be referring to the same class!

.getClass 方法将只返回对象的类。当您声明一个对象的新实例时,它将引用一个类。每个 jvm 只能有一个类,但有多个对象引用它。因此,当您获得两个对象的类时,它们可能指的是同一个类!