Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically inject a parent into a class hierarchy in Java?

Given an class hierarchy:

A -> B -> C -> instanceOfC

is it possible (and how) to insert a class, temporarily, at runtime, like so:

A -> B -> B' -> C -> instanceOfC?

like image 614
blueberryfields Avatar asked Feb 01 '11 06:02

blueberryfields


People also ask

Can we store parent object to child in Java?

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.

Can you access child class with parent reference?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.

Why do we assign a parent reference to the child object in Java?

Because Java is statically typed at compile time you get certain guarantees from the compiler but you are forced to follow rules in exchange or the code won't compile. Here, the relevant guarantee is that every instance of a subtype (e.g. Child ) can be used as an instance of its supertype (e.g. Parent ).

What keyword is used to inherit a parent class's state?

To inherit from a class, use the extends keyword.


1 Answers

AspectJ

It's possible if you use AspectJ. AspectJ has a declare parents statement that enables you to do exactly that, and through Load Time Weaving you should be able to do it at runtime, also. However, you will not be able to do it on already loaded classes (at least not easily, maybe it works if you unload the class first).

Reference:

  • AspectJ Quick Reference
  • AspectJ in Action (book)

Inheritance vs Aggregation

But methinks you are trying to solve the wrong problem here. I'd say try to replace inheritance with aggregation, let C have a member of type D to which functionality is delegated and just pass in a different implementation of D. That's called the strategy pattern, and it's a much cleaner way to do things (and it's testable too)

like image 113
Sean Patrick Floyd Avatar answered Nov 10 '22 07:11

Sean Patrick Floyd