title: How can I attempt to call a method on an object if that method isn't necessarily defined on that object?
body: <p>Java noob here so please treat me gently.  I have plenty of experience with duck-typed languages like Python and Ruby, but not much experience with statically-typed languages, and effectively zero Java experience.</p>
  
  <p>I have an array of objects which are all instances of the <a href="https://javadoc.jenkins-ci.org/hudson/model/Cause.html" rel="nofollow noreferrer"><code>Cause</code> class</a> (i.e. <code>ArrayList&lt;Cause&gt;</code>).  I would like to know if any of those objects have a property <code>upstreamRun</code> matching a particular value.  The problem is that only <a href="https://javadoc.jenkins-ci.org/hudson/model/Cause.UpstreamCause.html" rel="nofollow noreferrer"><code>UpstreamCause</code></a> objects have this property (<code>UpstreamCause</code> is a subclass of <code>Cause</code>), and not all of the objects in my array are <code>UpstreamCause</code> instances.</p>
  
  <p>Here is what I first tried:</p>
  
  <pre><code>causes.stream().anyMatch((Cause c) -&gt; c instanceof hudson.model.Cause.UpstreamCause &amp;&amp; c.getUpstreamRun() == run);
  </code></pre>
  
  <p>of course, this fails to compile because <code>upstreamRun()</code> is not defined on the <code>Cause</code> parent class:</p>
  
  <pre><code>[ERROR] /home/jay/local/data/sis/workspace/henlo-world-plugin/src/main/java/org/jenkinsci/plugins/sample/HelloWorldAction.java:[17,138] cannot find symbol
    symbol:   method getUpstreamRun()
    location: variable c of type hudson.model.Cause
  </code></pre>
  
  <p>I tried a few other approaches as well, but all of these failed to compile:</p>
  
  <pre><code>causes.stream().anyMatch((hudson.model.Cause.UpstreamCause c) -&gt; c instanceof hudson.model.Cause.UpstreamCause &amp;&amp; c.getUpstreamRun() == run);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>causes.stream().anyMatch((Cause c) -&gt; c.getClass().getMethod("getUpstreamRun", null) != null &amp;&amp; c.getClass().getMethod("getUpstreamRun").invoke(c) == run);
  </code></pre>
  
  <p>I know I'm probably approaching this the wrong way because, from what I understand, Java devs consider reflection and <code>instanceOf</code> to be code smells.  So what's the right way to go about this?</p>
  
  <p>If this were Ruby, I would do something like this:</p>
  
  <pre><code>causes.any? do |c|
    c.getUpstreamRun() == run
  rescue NoMethodError =&gt; e
    false
  end
  </code></pre>
  
  <p>But I'm guessing this kind of approach is shunned in Java, and even if it isn't, I have no idea how to write the equivalent in Java.</p>