私はJava 8が初めてで、Null型の注釈とオプションを試しています。
以下の例では、クラスではなく String を使用しており、何かを呼び出すためだけに toUpperCase を呼び出しています。私の場合、実際にはパラメーターを渡す関数を呼び出しています (したがって、:: 演算子やマップを使用できるとは思わないでください)。 )。
Eclipse では、Java - Compiler - Errors/Warnings - Null Analysis Errors がオンになっています。
以下の私のテストコード:
public void test1(@Nullable String s) {
// the 2nd s2 has a Potential null pointer access error.
// I was hoping ifPresent would imply NonNull
Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}
@Nullable
public String getSomeString() {
return null;
}
public void test2() {
String s = getSomeString();
// This is fine, unlike the first example, I would have assumed that
// it would know s was still nullable and behave the same way.
Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}
Eclipse 型の null アノテーションと Optional.ifPresent を使用するとうまくいかないようです。
このようなものを機能させるために時間を無駄にしていますか? ゲッターを一時変数に割り当ててからnullかどうかをチェックし、そうでない場合は関数を呼び出すことに戻る必要がありますか?