我试图动态调用类中的不同方法。
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;
}
}
这里我尝试使用refection从detFuncSet1类执行方法。但是getDeclaredMethod是一个原始类型,所以我无法将不同类型的输入传递给方法。
在上面的代码中,getDeclaredMethod具有参数类型的参数。根据我正在执行的查询,我得到了funcId(这是我的方法名称)。由于我的方法(在类detFuncSet1类中)具有不同的输入,我无法动态地将参数类型传递给getDeclaredMethod。有没有办法可以动态执行我的方法?
答案 0 :(得分:0)
通过反射,您将失去类型安全性。调用方法时,只需传递Object[]
数组。