dimanche 19 novembre 2017

Java reflection: Calling methods with different argument dynamically

I am trying to call different methods from a class dynamically.

detFunctions.java:

package detFunctions;

import java.lang.reflect.*;
import java.sql.*;  

public class detFunctions{
    public static void main(String[] args) throws Exception {
    String funcId = "";
    String funcName = "";
    String funcDesc = "";
    String Input = "";
    try{
        System.out.println("Retrieving Function for Execution....");

        Class.forName("oracle.jdbc.driver.OracleDriver");  
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.168.4:2921:SCRDEV","custom","custom");
        Statement stmt=con.createStatement(); 
        ResultSet rs=stmt.executeQuery("select FUNC_IDENTIFIER,FUNC_NAME,FUNC_DESC from custom.dfmt");
        Input = "10001|10002|10003";
        while(rs.next()){
            funcId = rs.getString("FUNC_IDENTIFIER");
            funcName = rs.getString("FUNC_NAME");
            funcDesc = rs.getString("FUNC_DESC");       
        }   
        con.close();
        System.out.println("Function execution completed!!!");
    } catch (Exception e){ System.out.println(e);} 
    System.out.println(funcId);
    System.out.println(funcName);
    System.out.println(funcDesc);
    System.out.println(Input);

    //Reflection of DETFunctions (Raw Type)
    String classId = "detFunctions.detFuncSet1";
    Class c = Class.forName(classId);
    Method m = c.getDeclaredMethod(funcId, new Class[] {String.class});
    Object i = c.newInstance();
    Object funcOutput = m.invoke(i, Input);
    System.out.println(funcOutput);


    //Reflection of DETFunctions (Generic Type)

  } //End of Main Function
} //End of class

*

detFuncSet1.java:

package detFunctions;

public class detFuncSet1 {

    public double GL_BALANCE(String GLList) {
        System.out.println("GL_BALANCE Method invoked.......");
        double GLBalance = 5005689.50;
        System.out.println("GL_BALANCE Method execution completed.....");
        return GLBalance;
  }

    public double EFF_BALANCE(String AcctNo,String InDate) {
        System.out.println("EFF_BALANCE Method invoked.......");
        double EFFBalance = 500.50;
        System.out.println("EFF_BALANCE Method execution completed.....");
        return EFFBalance;
  }
}

Here I am trying to execute methods from detFuncSet1 class using refection. But getDeclaredMethod is a raw type so I am not able to pass the inputs of different types to the methods.

In the above code, getDeclaredMethod has arguments which is parameter type. Based on the query i am executing I am deriving the funcId (which is my method name). Since my methods (in class detFuncSet1 class) are having different inputs I am not able to pass the parametertype dynamically to getDeclaredMethod. Is there a way i can execute my methods dynamically?





Aucun commentaire:

Enregistrer un commentaire