简体   繁体   中英

Is there a way to assign methods dynamically at runtime to a Java class?

Consider this base class:

public class Cat {
  public void meow() {
    // meowing
  }
}

And for some reason, cats subclasses can't inherit from this Cat class, because they MUST inherit from another base class, and Java doesn't support multiple inheritance. Thus:

public class Cat1 extends BaseClass1 {

}

public class Cat2 extends BaseClass2 {

}

public class Cat3 extends BaseClass3 {

}

How can I dynamically augment instances of CatX classes to inherit that meow method from Cat class?

A pseudo code might be:

public cat1Instance = new Cat1();
Cat.augmentWithCatBehavior(cat1Instance);

Is there a way for me to achieve this?

Update : Composition is not what I want. For composition, I need to have an instance of Cat class in all of my Cat1 to CatN classes. I have to create a wrapper method in each class so that I can call that meow . It's a huge amount of boilerplate code. That's why I said augmenting dynamically .

No, the structure of a Java class is fixed at compile time, and can only be inspected (using reflection) but not dynamically changed at runtime.

It is possible though to generate whole classes dynamically at runtime. Although that significantly defeats the purpose of using a statically compiled language, such as Java.

The other answer would be to look into AOP , which is supported in Java in some frameworks (for example in Spring AOP). Here the idea is to identify "crosscutting" concerns, and have the framework add the corresponding code in certain ways. A typical example of that would be to "annotate" methods to do "logging", and then the AOP framework just adds the code required to do some standardised logging.

Use an interface of Cat class instead of class and make your method default. Only for Java 8 and higher versions.

interface Cat {
   default void meow() {
    // meowing
   }
}
public class Cat1 extends BaseClass1 implements Cat {
    @Override public void meow() {}
}

And you can call the method of your child class as below:

Cat cat= new Cat1();
cat.meow();

You cannot add methods to a class at runtime. You have two possible solutions:

  1. Use an interface to work around the need for multiple inheritance.
  2. Use an instance field and composition instead of inheritance.

You can't do that but you have two options open to explore

  1. Using interface, its always good to use inheritance to assign behaviour rather than using inheritance.

  2. Second option is using functional programming to return Consumer instance from the method which can be changed based on some logical condition.

Note: Functional programming enabled us in returning functions/behaviour which can help us a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM