1

Assuming that I have a very basic case of polymorphism. How do I dynamically set which class to run during runtime?

E.g :

public interface Car {
      abstract String carName(); 
}

public class BMW implements Car{
    String carlogic(){
      // logic
    }
}


public class Audi implements Car{
    String carLogic(){
      //logic
   }
}

During runtime, I receive a string which is a car name. E.g. 'Audi','Bmw' etc. If i receive 'Audi' i want to call Audi.carLogic and 'BMW' BMW.carLogic. Now the easy way is to create this via switch cases but that seems rather messy? I know that this can also be done using reflections. But for the purpose of me learning, how would you approach this?

1 Answer 1

2

In a 'formal' application, I would be using Spring and @Qualifier annotation to choose the right implementation class. That's a lot of bloat to add to just a test case or simple application though.

Without using a framework, you would want to use a Factory pattern or similar pattern. A good example that closely matches your car scenario can be found here:

http://howtodoinjava.com/design-patterns/creational/implementing-factory-design-pattern-in-java/

Finally, because you appear to be prefixing the car implementation class to match the input String, reflection within the factory is not a bad choice. (P.S. using Groovy instead of just Java would make this even easier).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.