3

在Java中是否可以让一个类扩展一个泛型类型,以便您可以将一个方法注入到通过您的代码传递的任何类中?(或者有没有其他方法可以用 Java 将方法注入或覆盖到现有类中?)

我的意思是“扩展通用类型”是这样的(类“T扩展GameObject”属于游戏,可能不会更改并且未知,因为在运行时加载到游戏中(从其他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 由 GameEngine 调用,通过这种方式,我可以将每个现有的游戏对象替换为在每个刻度上向后移动的版本。

4

2 回答 2

8

不可以。您不能扩展泛型超类型。您可以扩展使用泛型类型的类(例如public class MyClass<T> extends TheirClass<T>),但不能扩展纯泛型类型。

于 2013-01-25T15:49:42.987 回答
0

在我看来,您可以找到解决方案,而不是在语言的特性中,而是在某些设计模式中,如装饰器模板方法模式

如果行为是在运行时确定的,您可以查看行为模式

于 2013-01-25T16:09:19.910 回答