유형 모드 일치 - CORBA 스타일
package io.github.ikysil.javaplayground.narrow;
import java.util.List;
import java.util.Optional;
public class TypeNarrowDemo {
static final class Types {
private Types() throws IllegalAccessException {
throw new IllegalAccessException();
}
static <T> T narrowToNull(final Object obj, final Class<T> expectedType) {
if (expectedType.isInstance(obj)) {
return expectedType.cast(obj);
}
return null;
}
static <T> Optional<T> narrow(final Object obj, final Class<T> expectedType) {
return Optional.ofNullable(obj)
.map(o -> narrowToNull(o, expectedType));
}
}
public static void main(String[] args) {
System.out.println("TypeNarrowDemo Demo");
if (Types.narrowToNull("test", Object.class) != null) {
System.out.println("SUCCESS: String is Object");
}
Types.narrow("test", Object.class)
.ifPresent(o -> System.out.println("SUCCESS: String is Object: " + o));
if (Types.narrowToNull("test", List.class) == null) {
System.out.println("SUCCESS: String is NOT List");
}
Types.narrow("test", List.class)
.ifPresentOrElse(
o -> System.out.println("ERROR: String is NOT List: " + o),
() -> System.out.println("SUCCESS: String is NOT List")
);
}
}
GitHub 라이브러리:java-playground
Reference
이 문제에 관하여(유형 모드 일치 - CORBA 스타일), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ikysil/type-pattern-matching-corba-style-2b73텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)