Varun Chawla
Varun Chawla

Reputation: 323

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.

Upvotes: 2

Views: 1819

Answers (1)

DwB
DwB

Reputation: 38290

TLDR
This design is terrible. Use an interface instead of reflection.

More Info
You are using Spring.
Spring is happy to inject dependencies into your controllers.
Spring is almost certainly guaranteed to do a better job injecting your dependencies than you are at performing reflection.
The calling interface of your service is fixed (notice that you hard-coded both the parameter types and the parameter order) which, interestingly enough, is the same as with an interface.

Upvotes: 2

Related Questions