Why does MyClass.class exist in java, but MyField.field does not?

Say I have:

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

Why does Java have this syntax: A.classand have no such syntax: b.field, c.method?

Is there any use that is so common for class literals?

+2
source share
4 answers

The syntax A.classlooks like access to a field, but in fact it is the result of a special syntax rule in a context where normal access to fields is simply not allowed; those. where Ais the name of the class.

Here's what the grammar says in JLS:

Primary:
  ParExpression
        NonWildcardTypeArguments (
            ExplicitGenericInvocationSuffix | this Arguments)
  this [Arguments]
  super SuperSuffix
  Literal
  new Creator
  Identifier { . Identifier }[ IdentifierSuffix]
  BasicType {[]} .class
  void.class

Note that for fieldor methodnot equivalent syntax.

( : b.field, JLS , b.field "field"... , . c.method , c. , , ...)

? , , Java / Field Method. (. * Java, .)

Java . Java , . . , .

, , . .

- , ?

, , , , , Class.forName("some horrible string") , - . / .

, , <type>.class , class . (IIRC, Java 1.1.)


* , :

  • , .
  • , , , , method field .
  • b.field , . b.field /. field , , field, Java.
  • c.method , , c. , c c, c.method method , c.

+6

, .. , , .

, . , , :)

+1

, . , A.class. API , :

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

Class c = A.class;

, c.

API , Java , , API- , ( , - ..).

b.field c.method , Java. , , . Java - , ( , ). , Ruby Javascript, Java, .

, , .

-1

java - .

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

A.class

With this, you get an object for the class.

With reflection, you can get methods and fields, but it gets complicated. Because not everything is an object. It 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 public / private / protected, so by default your things are declared as closed. This is secure access at the package level http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

-2
source

Source: https://habr.com/ru/post/1542195/


All Articles