在java中使用null进行类型转换时没有异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18723596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:30:11  来源:igfitidea点击:

No Exception while type casting with a null in java

javanullpointerexceptiontypecasting-operator

提问by Vicky

String x = (String) null;

Why there is no exception in this statement?

为什么这个说法没有例外?

String x = null;
System.out.println(x);

It prints null. But .toString()method should throw a null pointer exception.

它打印null. 但是.toString()方法应该抛出一个空指针异常。

采纳答案by Juned Ahsan

You can cast nullto any reference type without getting any exception.

您可以强制转换null为任何引用类型而不会出现任何异常。

The printlnmethod does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null". Otherwise it will call the toStringmethod of that object.

println方法不会抛出空指针,因为它首先检查对象是否为空。如果为 null 则它只是打印 string "null"。否则它将调用该toString对象的方法。

Adding more details:Internally print methods call String.valueOf(object)method on the input object. And in valueOfmethod, this check helps to avoid null pointer exception:

添加更多细节:内部打印方法调用String.valueOf(object)输入对象的方法。在valueOf方法中,此检查有助于避免空指针异常:

return (obj == null) ? "null" : obj.toString();

For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.

对于其余的混淆,如果不是特殊情况,则在空对象上调用任何方法都应该抛出空指针异常。

回答by rocketboy

Println(Object)uses String.valueOf()

Println(Object)用途 String.valueOf()

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Print(String)does null check.

Print(String)做空检查。

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

回答by André Stannek

This is by design. You can cast nullto any reference type. Otherwise you wouldn't be able to assign it to reference variables.

这是设计使然。您可以转换null为任何引用类型。否则,您将无法将其分配给引用变量。

回答by Jeroen Vannevel

Print:

打印

Print an object. The string produced by the String.valueOf(Object) method is translated into bytes

打印一个对象。String.valueOf(Object) 方法生成的字符串被转换为字节

ValueOf:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

如果参数为空,则字符串等于“空”;否则,返回 obj.toString() 的值。

It wil simply return a string with value "null" when the object is null.

当对象为 时,它将简单地返回一个值为“null”的字符串null

回答by Peter Lawrey

You can cast nullto any reference type. You can also call methods which handle a nullas an argument, e.g. System.out.println(Object)does, but you cannot reference a nullvalue and call a method on it.

您可以转换null为任何引用类型。您还可以调用将 anull作为参数处理的方法,例如System.out.println(Object)do,但您不能引用一个null值并对其调用方法。

BTW There is a tricky situation where it appears you can call static methods on nullvalues.

顺便说一句,有一种棘手的情况,您似乎可以对null值调用静态方法。

Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.

回答by Mewel

Casting null values is required for following construct where a method is overloaded and if null is passed to these overloaded methods then the compiler does not know how to clear up the ambiguity hence we need to typecast null in these cases:

在方法重载的以下构造中需要转换空值,如果将空值传递给这些重载方法,那么编译器不知道如何消除歧义,因此我们需要在这些情况下对空值进行类型转换:

class A {
  public void foo(Long l) {
    // do something with l
  }
  public void foo(String s) {
    // do something with s      
  }
}
new A().foo((String)null);
new A().foo((Long)null);

Otherwise you couldn't call the method you need.

否则你不能调用你需要的方法。

回答by Marten Jacobs

This is very handy when using a method that would otherwise be ambiguous. For example: JDialog has constructors with the following signatures:

这在使用否则会模棱两可的方法时非常方便。例如: JDialog 具有具有以下签名的构造函数:

JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)

I need to use this constructor, because I want to set the GraphicsConfiguration, but I have no parent for this dialog, so the first argument should be null. Using

我需要使用这个构造函数,因为我想设置 GraphicsConfiguration,但是我没有这个对话框的父级,所以第一个参数应该是空的。使用

JDialog(null, String, boolean, Graphicsconfiguration) 

is ambiguous, so in this case I can narrow the call by casting null to one of the supported types:

是不明确的,所以在这种情况下,我可以通过将 null 强制转换为支持的类型之一来缩小调用范围:

JDialog((Frame) null, String, boolean, GraphicsConfiguration)

回答by GhostCat

As others have written, you can cast null to everything. Normally, you wouldn't need that, you can write:

正如其他人所写,您可以将 null 强制转换为所有内容。通常,你不需要那个,你可以写:

String nullString = null;

without putting the cast there.

没有把演员放在那里。

But there are occasions where such casts make sense:

但在某些情况下,这种类型转换是有意义的:

a) if you want to make sure that a specific method is called, like:

a) 如果要确保调用特定方法,例如:

void foo(String bar) {  ... }
void foo(Object bar) {  ... }

then it would make a difference if you type

那么如果你输入它会有所作为

foo((String) null) vs. foo(null)

b) if you intend to use your IDE to generate code; for example I am typically writing unit tests like:

b) 如果您打算使用您的 IDE 生成代码;例如,我通常编写单元测试,如:

@Test(expected=NullPointerException.class)
public testCtorWithNullWhatever() {
    new MyClassUnderTest((Whatever) null);
}

I am doing TDD; this means that the class "MyClassUnderTest" probably doesn't exist yet. By writing down that code, I can then use my IDE to first generate the new class; and to then generate a constructor accepting a "Whatever" argument "out of the box" - the IDE can figure from my test that the constructor should take exactly one argument of type Whatever.

我在做TDD;这意味着“MyClassUnderTest”类可能还不存在。通过写下该代码,我可以使用我的 IDE 首先生成新类;然后生成一个构造函数,该构造函数接受“开箱即用”的“任何”参数 - IDE 可以从我的测试中得出,构造函数应该只采用一个任何类型的参数。

回答by Arigion

Many answers here already mention

这里的许多答案已经提到

You can cast null to any reference type

您可以将 null 强制转换为任何引用类型

and

If the argument is null, then a string equal to "null"

如果参数为空,则字符串等于“空”

I wondered where that is specified and looked it up the Java Specification:

我想知道它在哪里指定并查找了 Java 规范:

The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).

始终可以将空引用分配或强制转换为任何引用类型(第 5.2 节、第 5.3 节、第 5.5 节)。

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

如果引用为空,则将其转换为字符串“空”(四个 ASCII 字符 n、u、l、l)。

回答by Changgull Song

This language feature is convenient in this situation.

在这种情况下,此语言功能很方便。

public String getName() {
  return (String) memberHashMap.get("Name");
}

If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.

如果 memberHashMap.get("Name") 返回 null,您仍然希望上述方法返回 null 而不会引发异常。无论类是什么,null 都是 null。