Reputation: 1427
is it possible in Java to let a class extend a generic type, so that you can inject an method into any class passed through your code? (Or is there any other way to inject or override methods into an existing class with Java?)
What I mean with "extend a generic type" is something like this (Class "T extends GameObject" belongs to game and may not be changed AND is unknown because loaded into the game at runtime (from other mods)):
class GameObject {
void moveForward(float amount) {
this.camera.z += amount;
}
}
class Extender<T extends GameObject> extends T {
void onTick(float time) {
this.camera.z -= amount;
}
}
onTick is called by the GameEngine, and in this way I could replace every existing game object with a version that moves backwards on every tick.
Upvotes: 4
Views: 7906
Reputation: 1418
In my opinion you can find the solution not in language's features, but in some design pattern, as Decorator or Template Method Pattern.
If the behaviour is determinated in runtime, you could give a look at behaviour patterns.
Upvotes: 0
Reputation: 2434
No. You cannot extend a generic supertype. You can extend classes that make use of generic types (e.g. public class MyClass<T> extends TheirClass<T>
) but you cannot extend a purely generic type.
Upvotes: 8