samedi 13 février 2016

generate a class during runtime based on logic java

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?

Aucun commentaire:

Enregistrer un commentaire