有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

对象getClass在Java中是如何工作的

下面是JavaDoc所说的:

public final Class <?> 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.
The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass 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

因此,我的疑问在于:

  1. 此方法的返回类型
  2. 未调用toString方法。关于这个话题的类似帖子如下: Java. getClass() returns a class, how come I can get a string too?
  3. 注释代码,否则会产生编译时错误

共 (1) 个答案

  1. # 1 楼答案

    此时,我们需要区分该类型的typeinstance。让我们用一个例子来解释它

        public class A {
            public static void main(String[] args) {
                Class<A> typeInformation = A.class; //Type information associated with type `A`
                A instanceOfA = new A();  //actual instance of type `A`
            }   
        }
    

    类型

    上述代码中的引用“typeInformation”属于Class类型,暂时将泛型放在一边。这些信息通常位于非堆内存部分。针对每个typejvm加载存储以下信息:

    • 类型的完全限定名
    • 类型的直接超类的完全限定名(除非该类型是接口或类java.lang.Object,两者都没有超类)
    • 无论类型是类还是接口
    • 类型的修饰符(public、abstract、final的一些子集)
    • 任何直接上级界面的完全限定名称的有序列表

    实例

    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