Say I have two classes:
AnimalPen.java
public class AnimalPen {
private ArrayList<Animal> animals;
public AnimalPen() {
animals = new ArrayList<Animal>();
animals.add(new Dog("Freddy"));
animals.add(new Dog("Doggy"));
for (Animal a : animals) {
animal.makeSound();
}
}
}
Dog.java
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Woof");
}
}
Is there any possible way to use reflection to change what makeSound()
in dog does, without modifying either of these classes? For example (this is just a suggestion. I don't have the best understanding of reflection) I make a class called Dog
that extends Animal
, and then at runtime exchange the Dog.java
posted above with one that I created so that every single time new Dog()
is called, it will create a new instance of my Dog instead of the one written above. I need this in a way so that I don't need to be knowing when new instances of Dog are being created, but they are using the class that I made with a modified makeSound()
instead of the one that just prints out "Woof".
To give a better example, as an experiment I am trying to modify a Minecraft server without modifying the source code of the server itself. I am loading my code into the JVM via CraftBukkit and I want to directly change how entities behave by modifying methods in the entity classes and then loading them into the server. I know this is possible to do through reflection, I was just more or less wondering if it is possible to "swap" an entire class at runtime with a modified version of it.