mardi 31 juillet 2018

How can I attempt to call a method on an object if that method isn't necessarily defined on that object? [duplicate]

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.

I have an array of objects which are all instances of the Cause class (i.e. ArrayList<Cause>). I would like to know if any of those objects have a property upstreamRun matching a particular value. The problem is that only UpstreamCause objects have this property (UpstreamCause is a subclass of Cause), and not all of the objects in my array are UpstreamCause instances.

Here is what I first tried:

causes.stream().anyMatch((Cause c) -> c instanceof hudson.model.Cause.UpstreamCause && c.getUpstreamRun() == run);

of course, this fails to compile because upstreamRun() is not defined on the Cause parent class:

[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

I tried a few other approaches as well, but all of these failed to compile:

causes.stream().anyMatch((hudson.model.Cause.UpstreamCause c) -> c instanceof hudson.model.Cause.UpstreamCause && c.getUpstreamRun() == run);

and

causes.stream().anyMatch((Cause c) -> c.getClass().getMethod("getUpstreamRun", null) != null && c.getClass().getMethod("getUpstreamRun").invoke(c) == run);

I know I'm probably approaching this the wrong way because, from what I understand, Java devs consider reflection and instanceOf to be code smells. So what's the right way to go about this?

If this were Ruby, I would do something like this:

causes.any? do |c|
  c.getUpstreamRun() == run
rescue NoMethodError => e
  false
end

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.





Aucun commentaire:

Enregistrer un commentaire