In Java, can “void” be considered a primitive type?

后端 未结 7 1005
-上瘾入骨i
-上瘾入骨i 2021-01-17 10:21

I\'ve noticed eclipse JDT uses void as a primitive type. Can this be considered correct?

相关标签:
7条回答
  • 2021-01-17 10:30

    I find that, in cases like this, you can't beat going to the Java Language Specification. It is pretty clear about the fact that void is not a primitive.

    First off, void is not in the list of primitive types. Later on, the JLS explicitly states:

    the Java programming language does not allow a "cast to void" — void is not a type http://java.sun.com/docs/books/jls/third_edition/html/statements.html#5989 (emphasis mine)

    Furthermore, void appears in the list of keywords, not the list of literals.

    The reason that you saw what you did was explained nicely by Michael Borgwardt.

    So, to answer your title: no. In Java, void cannot be considered a primitive. To answer your body: yes, the Eclipse JDT code is correct for what it needs to do.

    0 讨论(0)
  • 2021-01-17 10:37

    I see you argue a lot about this but...

    hey guys, there is a function named isPrimitive() in java.lang.Class

    so why don't we invoke it with void class object and get the answer?

    besides, Void.TYPE is get using Class.getPrimitiveClass("void").

    So the fact is clear, void IS primitive.

    0 讨论(0)
  • 2021-01-17 10:42

    From your link:

    Note that "void" is special in that its only legitimate uses are as a method return type and as a type literal.

    Note also that this is a class concerned with AST nodes, i.e. the syntax of the Java language.

    Basically, when modelling the language syntax, void appears in some of the same places as primitive types, so when representing the syntax as a Java class, you have to classify it similarly.

    0 讨论(0)
  • 2021-01-17 10:46

    here is what written in javadoc you referenced:

    Type code for the primitive type "void". Note that "void" is special in that its only legitimate uses are as a method return type and as a type literal.

    Pay attention on the bold word. I think this explains everything.

    0 讨论(0)
  • 2021-01-17 10:49

    No void is not a primitive type. It is simply a keyword to indicate a method has no return value. The closest you can come is the java.lang.Void class, which from the Javadocs is described as:

    The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

    The presence in the JDT is merely to build the ASTs for the code. If you look at the field value description in the same docs it says:

    Type code for the primitive type "void". Note that "void" is special in that its only legitimate uses are as a method return type and as a type literal.

    0 讨论(0)
  • 2021-01-17 10:49

    as I know, void its not a primitive type. However they have this constant in the class Type for reflection reasons!

    0 讨论(0)
提交回复
热议问题