자바에서 ?:
을 에뮬레이트하는 라이브러리 메소드를 작성하고 있습니다.내 방법을 사용할 때 경고를 없앨 수 있습니까?
공정하게 말해서 나는 이것이 얼마나 유용한 지 확신 할 수 없으며 지금은 개인적으로 테스트하고 있습니다.
/**
* Shorthand for {@link #nullCoalescing(Object, Supplier, Object)}
*/
@NotNull
public static <RawType, BackupType> BackupType nc(
@Nullable RawType possiblyNullValueContainer,
@NotNull Supplier<BackupType> ifNotNull,
@NotNull BackupType nonNullBackup) {
return nullCoalescing(possiblyNullValueContainer, ifNotNull, nonNullBackup);
}
/**
* Null Coalescing method: If {@code possiblyNullValueContainer} is {@code null}, {@code nonNullBackup} is returned;
* else, {@code ifNotNull} is invoked and its result returned. The only caveat occurs when {@code
* possiblyNullValueContainer} is a non-null {@link Optional}, wherein its {@link Optional#isPresent() isPresent()}
* method is checked after discovering that it itself is not null.
*
* @param possiblyNullValueContainer The possibly-null value to check, or an {@link Optional} whose internal value
* is to be checked.
* @param ifNotNull If {@code possiblyNullValueContainer} is not {@code null}, this is invoked and
* its result returned. The intended use is that this references a method that can
* be called on the aforementioned object, like {@code() ->
* possiblyNullValueContainer.toString()}. If this is {@code null}, you're just
* being silly and {@code null} will be returned.
* @param nonNullBackup If {@code possiblyNullValueContainer} is {@code null}, this is returned.
* @param <RawType> The type of value to check for nullability
* @param <BackupType> The type of the backup values, which should not be null.
*
* @return Pretty much {@code possiblyNullValueContainer ? ifNotNull() : nonNullBackup}
*/
@NotNull
@SuppressWarnings("unchecked") // manually type-checked
public static <RawType, BackupType> BackupType nullCoalescing(
@Nullable RawType possiblyNullValueContainer,
@NotNull Supplier<BackupType> ifNotNull,
@NotNull BackupType nonNullBackup) {
if (null == possiblyNullValueContainer) {
return nonNullBackup;
} else if (possiblyNullValueContainer instanceof Optional) {
// If they pass us an Optional, they must want us to check if it has a value inside rather than itself
Optional nonNullOpt = (Optional) possiblyNullValueContainer;
if (!nonNullOpt.isPresent()) {
return nonNullBackup;
}
}
if (null == ifNotNull) {
Logger.getGlobal().severe("What are you doing?!");
return null;
} else {
return ifNotNull.get();
}
}
이는 등처럼 사용된다 : 잘 작동
// kinda like int i = value ?: 0
int i = nc(value,() -> value.intValue(), 0)
// less useful, I know, but still supported
String s = nc(optional ,() -> optional.get(), "simple");
합니다. 내가 좋아하는, 전체 메소드 이름을 사용할 때 문제가 온다 :
long l = nullCoalescing(value,() -> value.longValue(), 0L)
나는이 경고를 얻을 : 내가 수동으로 각각의 모든 라인을 확인하기 때문에,
명확 bubkus한다 메소드를 사용하는 동안 NPE가 던져 질 수 없도록하고, 심지어는 running tests against it으로 온건성 검사를하는 방법을 사용합니다. 그래서 누군가 내 nullCoalescing
방법을 사용할 때마다이 경고가 나타나지 않게하려면 어떻게해야합니까? nc
를 사용하는 경우
참고이가하는 발생하지 (그것이 어떤 깊이를 드릴하지 않습니다 아마도 때문에?).