问题
Can null
be casted to any type? i.e. will the following code work
public <T> T foo(Object object){
return (T) object;
}
Duck duck = foo(new Duck()); // this works
Duck duck2 = foo(null); // should this work?
Cat cat = foo(null); // should this work?
// if they are both null, should this be true?
boolean equality = duck2.equals(cat);
My question is, is null
'castable to anything'?
回答1:
From Javadocs:
There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.
回答2:
Yes those both should work but the key is you need to make sure you don't try to reference those fields or methods later. (at least until you have assigned those variables to something else)
All objects inherit Object
but since you assigned to null it won't actually have the methods or fields you would expect an Object
to have. So you will get an error here when you try to call equals()
because null does not have the methods you would normally inherit from object.
You can assign a variable you declare to null which can be very useful to prevent compiler errors if its actual value is defined in an if
statement.
来源:https://stackoverflow.com/questions/24208612/casting-null-to-any-type