java中的getType()和getClass()有什么区别?

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

what is the difference between getType() and getClass() in java?

javaclasstypes

提问by Elad Benda

I used to use getType()in c# and I see it exist in Java as well.

我曾经getType()在 c# 中使用过,我看到它也存在于 Java 中。

when should I use getType()and when getClass()?

我应该什么时候使用getType(),什么时候使用getClass()

采纳答案by DanielGibbs

According to the documentation for getClassand getType:

根据getClassgetType的文档:

getClassreturns "The Class object that represents the runtime class of this object."

getClass返回“表示此对象的运行时类的 Class 对象。”

getTypereturns "a Class object identifying the declared type of the field represented by this object"

getType返回“标识由该对象表示的字段的声明类型的类对象”

The main difference being that someObject.getClass()will give you a class object of the runtimetype of someObject, and someField.getType()will give you a class object of the declaredtype of the field that someFieldrefers to.

主要的区别是someObject.getClass()会给你的类对象的运行时类型的someObject,并且someField.getType()会给你的类对象中声明该字段的类型someField是指。

(Calling someField.getClass()will return Field.classbecause it's referring to the Fieldobject itself, not the field that it is referring to).

(调用someField.getClass()将返回,Field.class因为它指的是Field对象本身,而不是它所指的字段)。

Also, while getClassis available for every object, getTypeis only available on Fieldobjects which are part of the reflection API.

此外,虽然getClass可用于每个对象,但getType仅可用于Field属于反射 API 的对象。

回答by Saif

getClassis a method of Class Object which will be inherited to all the classes and will work same in every situation.
getTypeis just like some other method written on different classes for different purposes .

getClassClass Object 的一个方法,它将被继承到所有类,并且在任何情况下都相同。
getType就像为不同目的在不同类上编写的其他方法一样。

getClass()

获取类()

Returns the runtime class of this Object. The returned Class object is the object that is locked by
static synchronized methods of the represented class.

As the documentation says
And It is universal for all the classes that will be ever written on Java

正如 文档所说
,它对于所有将在 Java 上编写的类都是通用的

getType()Return different things on different situation

getType()在不同的情况下返回不同的东西

As for example

例如

In Charactermethod getTypeReturns a value indicating a character's general category.

字符方法中getTypeReturns a value indicating a character's general category.

In java.awt.Windowmethod getTypereturn Enum Window.Type

java.awt.Window方法中getType返回Enum Window.Type