Java 泛型类型键入的行为不符合预期
我有三个Java 泛型类型键入的行为不符合预期,java,generics,abstract-class,Java,Generics,Abstract Class,我有三个摘要类es: 公共抽象类着色器 公共抽象类ShaderInput 公共抽象类ShaderOutput 着色器类的主体非常简单: protected Function<ShaderInput, ShaderOutput> shader; public Shader(Function<ShaderInput, ShaderOutput> shader){ this.shader = shader; } public
摘要
类
es:
公共抽象类着色器
公共抽象类ShaderInput
公共抽象类ShaderOutput
着色器
类的主体非常简单:
protected Function<ShaderInput, ShaderOutput> shader;
public Shader(Function<ShaderInput, ShaderOutput> shader){
this.shader = shader;
}
public ShaderOuput render(ShaderInput input){
return shader.apply(input);
}
当我像上面那样键入传入的函数时,IDE会抱怨
未定义构造函数着色器(函数)
我会假设,因为VertexInput扩展了ShaderInput
和VertexOutput扩展了ShaderOutput
,这将起作用,并且能够为代码提供更高的可读性。在代码中,可以使用任何ShaderInput
调用渲染
,例如,SpecialInput类的扩展着色器输入
,它与顶点输入
不兼容
您可以这样更改您的类:
public abstract class Shader<T extends ShaderInput, U extends ShaderOutput> {
protected Function<T, U> shader;
public Shader(Function<T, U> shader) {
this.shader = shader;
}
public U render(T input) {
return shader.apply(input);
}
}
公共抽象类着色器{
保护函数着色器;
公共着色器(函数着色器){
this.shader=着色器;
}
公共U渲染(T输入){
返回着色器.apply(输入);
}
}
及
公共类VertexShader扩展着色器{
公共顶点着色器(函数VertexShader){
超级(顶点着色器);
}
}
另见:
您使用的是什么语言?我猜Java是因为super
?哦,谢谢,我忘了标记lang,我几乎没问过问题。我试过用不同的方法来绑定它,但没有用。你说“不能按如下方式编写”是什么意思?你有编译器错误吗?如果是,请出示。它是否编译但不工作?请解释预期行为与实际行为。@Sentry编辑了我的问题为什么不直接说public U render(T input){
@Lino谢谢,我错过了您可能还想将函数更改为Function@Lino我相信你是对的,但我不能完全理解你的思路。不过,如果我的答案保持正确,请随意编辑;)一个函数
public abstract class Shader<T extends ShaderInput, U extends ShaderOutput> {
protected Function<T, U> shader;
public Shader(Function<T, U> shader) {
this.shader = shader;
}
public U render(T input) {
return shader.apply(input);
}
}
public class VertexShader extends Shader<VertexInput, VertexOutput> {
public VertexShader(Function<VertexInput, VertexOutput> vertexShader) {
super(vertexShader);
}
}