tags:

views:

207

answers:

2
  String fullName = PATH + "." + name;
  Class cl= Class.forName(fullName);
  if(name.equalsIgnoreCase("MobileSearch")){
   if(msearchType==null){
    msearchType=(SearchInterface)cl.newInstance();
   }
   return msearchType;

  }
  if(name.equalsIgnoreCase("BookSearch")){
   if(bsearchType==null){
    bsearchType=(SearchInterface)cl.newInstance();
   }
   return bsearchType;

  }

How do I get rid of the if statements here.
I am using reflection.
Please help. Thanks in advance.

A: 

Are you just returning an instance of a SearchInterface? If so why not:

String fullName = PATH + "." + name;

Class cl= Class.forName(fullName);                
if(searchType==null){                                
     searchType=(SearchInterface)cl.newInstance();
}                        
return searchType;

Hope that helps.

jschoen
i need to create only a single instance i.e a singleton and i have multiple domains.as shown in the snippet i posted i check if each domain object is null before i create the instance.i want a work around for that. please help.
@Sam - use Nicks solution it should solve your problem, by using a Map. If it is not in the map then you create the instance, and it reduces the number of if statements in your code. Plus in the future if you add more SearchInterface types you will not need to change your code unless the path change
jschoen
+2  A: 

Use a Map:

if (!searchInstances.containsKey(name)) 
{
  searchInstances.put(
    name, 
    (SearchInterface)Class.forName(PATH + "." + name).newInstance()
  );
}

return searchInstances.get(name);
Nick Holt