Search code examples
classdynamicreflectionfactoryfactory-pattern

Refecltion - Dynamic class invocation


The following is the code where if else is used. If i need to dynamically create a class. how can i do it? is Reflection used ? If so : how can i implement the same using reflection?

  public static Pizza getConcretePizza(String PType)
 { 
   Pizza p=null;
    if (PType.equals("Cheese")) 
      {
           p=new CheesePizza();
         //ResultIng = cp.FetchIng();
      } else if (PType.equals("Pepperoni")) 
      {
         p=new PepperoniPizza();
        // ResultIng = pp.FetchIng();
      }
      else if (PType.equals("Clam")) 
      {
          p = new CalmPizza();
          //ResultIng = cap.FetchIng();
      }
       else if (PType.equals("Veggie")) 
      {
         p= new VeggiePizza();
         // ResultIng = vp.FetchIng();
      }
       return(p); 
     }   

Solution

  • I tried getting the answer and finally found the solution.

    (INSTEAD OF THE IF _ ELSE WE NEED TO REPLACE THE FOLLWOING CODE)

            Class<?> clazz = Class.forName("PizzaTrail." + PType);
            Object instance = clazz.newInstance();
            p = (Pizza) instance;
            return (p);
    

    the above code will resolve the issue of writing the if else and reflection will help calling the class dynamically.