dimanche 17 mars 2019

Using reflection in method of spring service

I have registered a service in my spring application. I have some methods with almost same nomenclature. So I am using reflection for invoking them to avoid using if else. Below is the similar scenario.

@Service
public class MyService {
public List<String> getEmployee(String type) {
Class myServiceClass = Class.forName("MyService");
Class partypes[] = new Class[1];
partypes[0] = String.class;
Method meth = myServiceClass.getDeclaredMethod("getEmpBy"+type, partypes);
Object arglist[] = new Object[1];
arglist[0] = type;
meth.invoke(this, arglist);
}
}

Now I have methods with nomenclature as getEmpByName, getEmpByAddress, getEmpByQualification. To avoid if else I want to use reflection but the above code is giving not able to load MyService at runtime.





Aucun commentaire:

Enregistrer un commentaire