简体   繁体   中英

Why does Eclipse say that null is a primitive type?

I wrote this line of code in Eclipse Mars for messing purposes:

null.toString();

And I got the following compiler error message:

Cannot invoke toString() on the primitive type null

Which is very strange since null is not a primitive type nor an object reference as explained here: Is null an Object?

So, just to be sure, I tried to compile such odd line of code using javac and I got this result:

 NullTest.java:3: <nulltype> cannot be dereferenced null.toString(); ^ 1 error

Does somebody know why Eclipse would give such (IMO) misleading compiler error message?

Since the null-type is a subtype of Object , it's conceivably OK to invoke Object methods on null .

However, following that logic, since the null-type is a subtype of every reference type, we should be allowed to invoke any method of any class/interface on null . That'll be a mess.

Syntactically, null.toString() should be recognized as a method invocation expression at first, because null is a Primary expression. Then, to determine the class/interface to search for the method toString , JLS says

...The class or interface to search is T if T is a class or interface type, or the upper bound of T if T is a type variable

It is a compile-time error if T is not a reference type.

T is the null-type here; it is not a class type, interface type, or type variable, therefore this step should fail. However, does it fail because T is not a reference type ?

Is the null-type a reference type? JLS says

The types ... are divided into two categories: primitive types and reference types

The numeric types are ....

The reference types are class types, interface types, [type variables,] and array types . [period!]

There is also a special null type .

Depending on your parsing of the text, null-type may or may not be a reference type. That is usually not really important; it's just a matter of categorization. But it leads to confusions, for example in this case -- the failure is because T is not a "proper" reference type, and the compiler deduces by mistake that it must be a primitive type then.

There is no reason.

Usually eclipse analyze the bytecode and for some reason null.toString() are two bytecode-statements, a definition and a call. Because you can call toString only on objects, eclipse assumes the declaraion must declare a primitive.

You can write a Bugreport but think about the overhead that may come with the internationalization of the error-message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM