本文介绍了用Java扩展泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的意思是扩展泛型类型是这样的T扩展游戏对象属于游戏,并且可能不会被改变,因为在运行时加载到游戏中(来自其他mod),所以不知道它是否是未知的:

  class GameObject {
void moveForward(float amount){
this.camera.z + = amount;
}
}

class Extender< T扩展了GameObject>扩展T {
void onTick(float time){
this.camera.z - = amount;
}
}

onTick由GameEngine调用,并以这种方式我可以用一个在每次打勾时向后移动的版本来替换每个现有的游戏对象。 解决方案

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


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.

解决方案

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.

这篇关于用Java扩展泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:55