尝试返回null时的NPE

时间:2017-01-17 11:19:12

标签: java nullpointerexception

当使用null调用toFloat时,该程序应该避免使用null。    但是我还在接受NPE ......任何帮助

private static Float toFloat(Float def, String str) { try { return str != null ? Float.parseFloat(str) : def; } catch (NumberFormatException e) { return def; } }

 NSString *urlString = @"http://res.cloudinary.com/dep7kjzyg/video/upload/v1484562338/jol8unlgazw0awwhaidf.mov";
 NSURL *url = [NSURL URLWithString:urlString];
            self.item = [AVPlayerItem playerItemWithURL:url];
            self.player = [[AVPlayer alloc] initWithPlayerItem:self.item];
            AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.item];
            playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

        playerLayer.backgroundColor = [UIColor greenColor].CGColor;
        [self.view.layer addSublayer:playerLayer];
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.player play];
        self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

1 个答案:

答案 0 :(得分:14)

非常微妙。 Float.parseFloat返回float,而不是Float。条件运算符的后两个操作数必须属于同一类型,但是您要给它floatFloat.parseFloat的结果)和Floatdef )。编译器选择float,因为Float可以通过自动取消装箱强制转换为float

所以编译器输出的内容就好像你写的那样:

private static Float toFloat(Float def, String str) {
    try {
        return str != null ? Float.parseFloat(str) : def.floatValue();
        // Note ----------------------------------------^^^^^^^^^^^^^
    } catch (NumberFormatException e) {
        return def;
    }
}

...当然,在floatValue上调用null会引发NPE。

您可以通过确保第二个操作数的类型为Float而不是float来修复它。有很多方法可以做到这一点,但作为Zefick points out,最简单的是Float.valueOf(String)

private static Float toFloat(Float def, String str) {
    try {
        return str != null ? Float.valueOf(str) : def;
    } catch (NumberFormatException e) {
        return def;
    }
}