Choose class implementation at compile time

Suppose I have an interface Animaland specific classes that implement it Catand Dog. Right at the entrance to the program, here's what:

if (choice == 0) {
    Animal A = new Cat();
}
else if (choice == 1) {
    Animal A = new Dog();
}

I want the parameter to choicebe populated at compile time (e.g. during Maven build) so that:

  • If I compile with option == 0, the Dog class will not compile
  • If I compile with option == 1, the Cat class will not compile

The reason for this is that the classes "Cat" and "Dog" have different / different dependencies.

Basically, the goal is to have one assembly for "A is the cat" and the other for "A is the dog." When I pack the JAR, the precedent for launching the JAR will be either for "Cat" or for "Dog" (depending on the environment), never "Cat" and "Dog" - so there is no need for all dependencies to be in the project .

What is the best way to achieve this?

+4
source share
3 answers

You can move two implementations Animalinto two separate projects. Each project may have its own dependencies. Then you can package both projects independently of each other (including the corresponding dependencies), and only one implementation Animalwill be known at runtime.

You might end up with something like this:

base-animals
  ├ com.wang.animals.base.Animal
  └ com.wang.animals.base.AnimalFactory

dog-application
  ├ com.wang.animals.dogs.Dog
  └ application.properties // animalClass=com.wang.animals.dogs.Dog

cat-application
  ├ com.wang.animals.cats.Cat
  └ application.properties // animalClass=com.wang.animals.cats.Cat

dog-application cat-application base-animals , , , . dog-application.jar cat-application.jar, / .

, Animal , AnimalFactory, Animal - ( ):

public class AnimalFactory {

  public static Animal createAnimal() throws Exception {
    final String animalClassName = getThisValueFromApplicationProperties();
    return Class.forName(animalClassName).getConstructor().newInstance();
  }
}

, Cat Dog , base-animals application.properties dog-application cat-application. , Cat Dog.

+3

"" , , .

static final int choice = 0;

, ? , , , JAR. , Maven .

+3

, Dog Cat Cat Dog.

, Dog Cat , . Anywhere, Cat Dog, Animal.

Class.forName Cat Dog, isSubclass , Animal, , Animal.

, , cat.jar dog.jar, . - , ..

+2

Source: https://habr.com/ru/post/1689707/


All Articles