@Test public void canCast() { Object foo = new Foo(){}; assertEquals(foo, Util.tryCast(foo, Foo.class).get()); assertEquals(false, Util.tryCast("foo", Foo.class).isPresent()); assertEquals(false, Util.tryCast(null, Foo.class).isPresent()); assertEquals(true, Util.tryCast(new Bar(), Foo.class).isPresent()); }
static <T, M extends T> Optional<M> tryCast(T original, Class<M> too) { if (original != null && too.isAssignableFrom(original.getClass())) { return Optional.of((M) original); } return Optional.empty(); }
Util { static <T, M extends T> Optional<M> tryCast(T original, Class<M> too) { if (original != null && too.isAssignableFrom(original.getClass())) { return Optional.of((M) original); } return Optional.empty(); } }
Util { static <T, M extends T> Optional<M> tryCast(T original, Class<M> too) { if (original != null && too.isAssignableFrom(original.getClass())) { return Optional.of((M) original); } return Optional.empty(); }  }
Util { static <T, M extends T> Optional<M> tryCast(T original, Class<M> too) { if (original != null && too.isAssignableFrom(original.getClass())) { return Optional.of((M) original); } return Optional.empty(); }   }
Util { static <T, M extends T> Optional<M> tryCast(T original, Class<M> too) { if (original != null && too.isAssignableFrom(original.getClass())) { return Optional.of((M) original); } return Optional.empty(); }    }