why MyClass.class exists in java and MyField.field isn't?

后端 未结 4 545
南笙
南笙 2021-01-23 05:15

Let\'s say I have:

class A {
    Integer b;
    void c() {}
}

Why does Java have this syntax: A.class, and doesn\'t have a syntax

4条回答
  •  清歌不尽
    2021-01-23 05:25

    In java, Not everything is an object.

    You can have

    A a = new A()
    Class cls = a.getClass()
    

    or directly from the class

    A.class
    

    With this you get the object for the class.

    With reflection you can get methods and fields but this gets complicated. Since not everything is an object. This is not a language like Scala or Ruby where everything is an object. Reflection tutorial : http://download.oracle.com/javase/tutorial/reflect/index.html

    BTW: You did not specify the public/private/protected , so by default your things are declared package private. This is package level protected access http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

提交回复
热议问题