Tuesday, August 11, 2015

[Java] Reflection

Sample classes that uses reflection.

1. Create interface class to define a contract (optional).

interface FactoryInterface {

   public void hello();

}

2. Create implementation class.

public class FactoryImpl implements FactoryInterface {

   @Override
   public void hello() {
      System.out.println("Hello world!");
   }

}

3. Create main class.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FactoryTest {


   public static void main(String[] args) {

      try {
         final Class<?> c = Class.forName("FactoryImpl");
         final Object implClassInstance = c.newInstance();
         Method classMethod = implClassInstance.getClass().
                              getMethod("hello", null);
         classMethod.invoke(implClassInstance, null);

      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      } catch (SecurityException e) {
         e.printStackTrace();
      } catch (InstantiationException e) {
         e.printStackTrace();
      } catch (IllegalAccessException e) {
 e.printStackTrace();
      } catch (NoSuchMethodException e) {
 e.printStackTrace();
      } catch (IllegalArgumentException e) {
e.printStackTrace();
      } catch (InvocationTargetException e) {
e.printStackTrace();
      }

   }

}

No comments:

Post a Comment