jeudi 1 novembre 2018

Problem in connecting to DB by using Java reflect in Spring boot application

My goal is to dynamically call a method using a method name which is a string. I am working on Spring boot application and Java reflect. All other places in the project, the same data source code is working fine and I am able to access the DB. But when I am using reflect, I am getting NullPointerException while initialising the connection object.

The following is the code of the class

public class Procedures implements Procedure {
    @Autowired
    private DataSource dataSource;
    Connection connection = null;
    public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
    }
    @Override
    public String calculateValue(String inputValue) {
        try {
        connection = dataSource.getConnection();
        ...
       return resultValue;
    }
    ...
}

And in my main class, I was calling the above class method using the following code.

try {
    String procedureName = "calculateValue";
    Class<?> callableClass = Class.forName("com.package.daoimpl.Procedures");
    Object callableClassObject = callableClass.newInstance();
    Method[] allMethods = callableClass.getDeclaredMethods();
    Method callableMethod = null;
    for (Method m : allMethods) {
        String mname = m.getName();
        if(mname.equals(procedureName)) {
            callableMethod = m;
        }
    }
    out.format("invoking %s()%n", procedureName);
    if(callableMethod != null) {
        String resultString = "";
        callableMethod.setAccessible(true);
        Object resultObject = null;
        if(callableMethod.getGenericReturnType() == String.class) {
            resultObject = callableMethod.invoke(callableClassObject, inputValue);
            resultString = (String) resultObject;
            ...
        }
    }                   
}
catch(Exception exp) {
    exp.printStackTrace();
}

Anyone please tell me what is wrong/what need to be done to achieve the DB connection?

Thank you in advance.





Aucun commentaire:

Enregistrer un commentaire