1

If I have three Classes (Foo, Bar and FooBar), how can I check for instance inside a Stream in Java 8?

Is there anything like:

Foo foo = new Foo();
if (Stream.of<Class>(Foo.class, Bar.class, FooBar.class).anyMatch(c -> foo instanceof c)) {
  System.out.println("yes");
}

I want to avoid things like:

if (foo instnaceof Foo || foo instanceof Bar || foo instanceof FooBar) {...}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
J. Doe
  • 23
  • 2
  • What exactly is `c`? If it is an instance of [`Class`](https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html), you could use [`c.isAssignableForm(....)`](https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class-) or something similar. If `c` is a generic parameter, than you are out of luck. – Turing85 Feb 01 '18 at 13:23
  • @Turing85 Evidently `c` is an instance of `Class`, because it is part of a `Stream`. – khelwood Feb 01 '18 at 13:26
  • Isn't this question much more specific than the duplicate of flagged question? – G_V Feb 01 '18 at 13:49
  • @G_V in which regard? The other question has an answer that perfectly answers this question as well. Does the intent to use this construct in a Stream change anything about it? – Holger Feb 01 '18 at 14:36
  • @Holger - Ah, so the Java 8 part of the question was not added for any particular reason then, since it's the same as earlier versions. – G_V Feb 01 '18 at 14:50
  • 1
    @G_V there is nothing wrong with providing additional context information from the OP’s side. If the OP knew that there is a simple solution that works independently to the Java 8 constructs he likely did not include this irrelevant context, but, of course, he can’t know it before asking… That’s also the reason why closed duplicate questions are kept. Future readers might as well search for key words of this question and will get redirected to the answered question. – Holger Feb 01 '18 at 14:57

1 Answers1

0

I am not quite sure if this is what you are looking for: instead of foo instnaceof Foo we can use method reference Foo.class::isInstance combined with a Predicate

Stream.of(/* your objects here */)
        .anyMatch(
            ((Predicate)(Foo.class::isInstance))
                    .or(FooBar.class::isInstance)
                    .or(Bar.class::isInstance)
        );
 }

We need to cast method reference Foo.class::isInstance to Predicate and after it we can combine it with other Predicates using Predicate#or method.

I hope this helps.

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53