title: Is there a way to check if a class has a method and then invoke it on an already existing instance of the object?
body: <p>I have this odd case which I'd like to handle through reflection or some library, if possible.
  Is there a way to check if a class has a method and then invoke it on an already existing instance of the object?</p>
  
  <p>For example, let's say I have:</p>
  
  <pre><code>Foo foo = new Foo();
  </code></pre>
  
  <p><code>Foo</code> has a <code>close()</code> method. Let's say I know that a lot of the classes will have a <code>close()</code> method but since they were poorly devised and are legacy that I cannot re-write, I would like to find out a generic solution to invoke a method I know they all have, despite them not inheriting from a base class or interface.</p>
  
  <p>I would like to have a method in my <code>FooHandling</code> class that accepts initialized objects and invokes their <code>close()</code> method. The objects will by no means inherit from the same base class, so they're totally different in nature, but all have a method with the same name. So, in <code>FooHandler</code> I'd like to have something like this:</p>
  
  <pre><code>void coolGenericClosingMethod(Object o)
  {
      // 1) Check via reflection if the class `o` represents contains a `close()`
      // 2) Invoke the method, if it exists, but on the passed in object `o`.
  }
  </code></pre>
  
  <p>So is there some neat trick I could use on an already instantiated object and still do that?</p>