Java implementation - Meta classes

北慕城南 提交于 2019-12-30 01:01:05

问题


The way I understand it, Java object model is 3 levels, each level describes the level beneath it, therefore there is one Meta class shared by all Classes (which are themselves objects?).

My question is - how are constructors implemented in Java? (or any other class methods) my logic says that constructors should appear in the Meta classes, but since there is only one Meta class, it doesn't make any sense that it keeps all possible constructors, or is my understanding of this is all wrong..


回答1:


In Java there's a single metaclass: the instances of the class Class are used to represent the types of classes and interfaces. The constructors are defined at the class level, not at the metaclass level.




回答2:


Your question targets nothing special about constructors: From the point of describing classes on a metalevel there is the same concept for constructors, "normal methods" and fields.

So think of it this way:

  • Each class in Java is described by a certain set of informations:

    • Name of the class
    • the superclass
    • the implemented interfaces
    • a list of constructors and their signatures
    • a list of (static and non-static) methods and their signatures
    • a list of (static and non-static) fields and their types
  • For your convenience this information is available to you during runtime - this is the "reflection API".

  • Since the same type of information is available for each class loaded by the JVM, this is bundled in a own class named java.lang.Class.

  • So one instance of the class Class describes the class java.lang.String, another instance of Class describes my.own.class.Foo.

  • java.lang.Class itself is of course also a class - therefore there also exists an instance of Class describing the class Class. And I think that's where things get recursive somehow.

Summary: There is only one metaclass: java.lang.Class. Multiple instances (meta-instance?) of the metaclass describe individual classes - including the metaclass itself. Constructor descriptions are part of the instances of the metaclass.



来源:https://stackoverflow.com/questions/9344156/java-implementation-meta-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!