title: Run a java method by passing class name and method name as parameter
body: <p>I am trying to make a program that executes a particular method when the class name and method name are passed as String parameter to the caller. Consider the code below. I have a class CarBean :</p>
  
  <pre><code>public class CarBean {
  
      private String brand;
      private String color;
  
      /**
       * @return the brand
       */
      public String getBrand() {
          return brand;
      }
  
      /**
       * @param the brand to set
       */
      public void setBrand(String brand) {
          this.brand= brand;
      }
  
      /**
       * @return the color
       */
      public String getColor() {
          return color;
      }
  
      /**
       * @param the color to set
       */
      public void setColor(String color) {
          this.color= color;
      }
  
  }
  </code></pre>
  
  <p>Now I want to run this via a method as below :</p>
  
  <pre><code>runTheMehod("CarBean","getColor");
  </code></pre>
  
  <p>The implementation of runTheMethod would be like this :</p>
  
  <pre><code>public runTheMethod(String className, String methodName){
  try {
              Object carObj = Class.forName(className).newInstance();
              //What to do now???
          } catch (InstantiationException | IllegalAccessException
                  | ClassNotFoundException e) {
              e.printStackTrace();
          }
  }
  </code></pre>
  
  <p>I can get an object using the class name. Now I need to cast it to a CarBean object and then I can run its method. So wondering how to cast it at runtime as the classname would be different for each call. Also, can I check whether the class has specific method before I try call it?</p>
  
  <p>Any suggestion on the problem would be appreciated. Also, I'm all ears to know if there is a better approach to do this.</p>