Tuesday

Dynamically calling a class - method in java by using reflection

Dynamically call a method on a dynamically given class by using reflection:
import java.lang.reflect.Method;

try {
       String myClassName = "tr.com.xx.xx.xx.Example";
       String myMethodName = "exampleMethod";

       Class<?> myClassRef = Class.forName(myClassName);
       Object instanceOfMyClass = myClassRef.newInstance();
       
       //my object input types in order: param1(int), param2(String), param3(MyDTO), param4(List<MyDTO>)
       Method method = myClassRef.getDeclaredMethod(myMethodName, int.class, String.class, MyDTO.class, List.class);
       MyResult respoonse = (MyResult) method.invoke(instanceOfMyClass, param1, param2, param3, param4);
       System.out.println("response" + response.getX());

} catch(Exception e) {
       //logging
       System.out.println(e.getMessage());

No comments:

Post a Comment