简体   繁体   English

Java用特定类型扩展超类的泛型方法

[英]Java extend generic method of superclass with specific type

Say I have the following interface: 说我有以下界面:

public interface Renderer {
...
    public <T> void setBackingGraphics(T t);
}

How do I now implement the interface in a way that specifies what specific "T" to use? 现在如何以指定要使用的特定“ T”的方式实现接口?

@Override
public <Graphics> void setBackingGraphics(Graphics t) {
    ...
}

The above obviously doesn't work because "Graphics" will just be considered to be another placeholder. 上面的方法显然不起作用,因为“图形”将被视为另一个占位符。 How do I actually make it "usable"? 我实际上如何使其“可用”? Let me demonstrate what I mean by using generic classes as example: 让我通过使用通用类作为示例来说明我的意思:

public interface A<T> {
    T someT();
}
public class C extends A<B> {
    B someT(){...}
}

How does the above work if I only want to apply it to specific methods? 如果我只想将其应用于特定方法,上述方法如何工作?

You need to be able to call the Renderer setBackingGraphics with any Object so the only thing you can do is: 您需要能够使用任何Object调用Renderer setBackingGraphics ,因此您唯一可以做的就是:

@Override
public void setBackingGraphics(Object t) {
}

If you want something more specific you need to bound your parameter, for example: 如果需要更具体的信息,则需要绑定参数,例如:

public interface Renderer {
    public <T extends String> void setBackingGraphics(T t);
}

And then you can do: 然后您可以执行以下操作:

@Override
public void setBackingGraphics(String t) {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM