对象getClass在Java中是如何工作的
下面是JavaDoc所说的:
public final Class <?> getClass()
Returns the runtime class of this
Object
. The returnedClass
object is the object that is locked bystatic synchronized
methods of the represented class.
The actual result type isClass<? extends |X|>
where|X|
is the erasure of the static type of the expression on whichgetClass
is called. For example, no cast is required in this code fragment:Number n = 0; Class<? extends Number> c = n.getClass();
Returns:
The Class object that represents the runtime class of this object.
现在,我知道它是一种本机方法,所以它是在依赖于平台的代码中实现的。但是这个方法的返回类型呢
public final Class<?> getClass()
也要考虑代码:
class Dog
{
@Override
public String toString()
{
return "cat";
}
}
public class Main
{
public static void main(String[] args)
{
Dog d= new Dog();
//Class<Dog> dd = new Dog(); Compile time error
System.out.println(d.getClass());
}
}
输出:
class Dog
因此,我的疑问在于:
- 此方法的返回类型
- 未调用toString方法。关于这个话题的类似帖子如下: Java. getClass() returns a class, how come I can get a string too?
- 注释代码,否则会产生编译时错误李>
# 1 楼答案
此时,我们需要区分该类型的
type
和instance
。让我们用一个例子来解释它类型
上述代码中的引用“typeInformation”属于
Class
类型,暂时将泛型放在一边。这些信息通常位于非堆内存部分。针对每个type
jvm加载存储以下信息:实例
Instanceofa是对
A
类型的实际实例的引用,它指向堆内存中的地址getClass()的返回类型是泛型
Class
类型。像java中的许多其他type
一样,String、Integer等,类也是一种表示相关类型信息的类型toString()方法是在Dog类的
instance
上关联和调用的,而不是在Dog类型本身上//Class<Dog> dd = new Dog(); Compile time error
这是由于在将右侧表达式的结果指定给左侧表达式时发生类型不匹配,而左侧表达式的类型不同。 类dd指的是类类型的引用。 Dog是一种完全不同的类型,可以将一个新的Dog()分配给“Dog”类型的引用
This link will help you understand the design aspects of java runtime environment