2016-09-29 54 views
1

我可以以某种方式部分实现一类泛型类型吗?我想实现的是,只有当somone真的依赖这种类型时,我才能接受通用的。看到的是我要寻找一个示范的目的以下富/酒吧例如:我能以某种方式部分实现一类单类泛型吗?

import java.util.Date; 

public class Sample { 
    public static abstract class ASomeFunc<AK, AV, PK, PV> { 

     public void forwardTo(ASomeFunc<?, ?, PK, PV> lala) { 

     } 

     // EDIT 1: 
     // we do some logic here and then pass a map entry to an actual implementation 
     // but somethimes I do not care what the key is I am just interested in what the value is 
     // public abstract Map.Entry<PK, PV> compute(Map.Entry<AK, AV> data); 
    } 

    public static class SomeFunc2 extends ASomeFunc<Date, String, Number, Number> { 

    } 


    // what I would like to do: 
    // public static class SomeOtherFunc extends ASomeFunc<?, Number, ?, Number> { 
    // but I ony can: 
    public static class SomeOtherFunc extends ASomeFunc<Object, Number, Object, Number> { 

    } 

    public static void main(String[] args) { 
     // but this now clashes ... sinc object is explicitly defined 
     new SomeFunc2().forwardTo(new SomeOtherFunc()); 
    } 
} 
+2

您是否正在寻找C++中“模板特化”的等价物?如果积极,准备失望。搜索“type erasure Java泛型” –

+2

为什么子类不依赖于该类型?抽象类可能过于专业化了吗? – Will

+1

实际上它不会编译,因为根据'forwardTo'和'SomeFunc2'的类型,'SomeOtherFunc'预计为'ASomeFunc <?,?,Number,Number>'类型,而其最后2个参数类型是'对象'和'数字' –

回答

1

?将不能工作,倒数第二个类型参数必须是完全Number(因为泛型是不变的)。

你也许可以通过一些不受控制的转换来解决它(一个丑陋的解决方案)。或者,如果,PK是消费者类型,使用方法:

forwardTo(ASomeFunc<?, ?, ? super PK, PV> lala) 

这也将让你的榜样编译。 (另见,PECS

但你的情况意味着你只是实现了ASomeFunc与你的子类的接口的一部分。

在这种情况下,您应该尝试分割ASomeFunc的接口,以便每个子类都可以精确地选择他们需要实现的内容,但仅此而已。

+0

是的,我只实现一个接口的一个opart。可悲的是,这个界面在'Map.Entry '上运行,但是有些事情我只是不在乎关键,而只是消耗了价值。看到我的编辑剪切代码。 – KIC

相关问题