2010-07-21 30 views
1

我收到此错误与下面的代码:使用Eclipse太阳神与JDK 1.6.0_16泛型示例不起作用?替代方案或建议?

The method getItemProperty(capture#2-of ? extends GenericTest.Item) in the type GenericTest.BaseContainer<capture#2-of ? extends GenericTest.Item> is not applicable for the arguments (GenericTest.Item)

import org.junit.Test; 

public class GenericTest { 

public class Item { 
    private String value; 

    public String getValue() { 
     return value; 
    } 

    public void setValue(String value) { 
     this.value = value; 
    } 
} 

public class WordItem extends Item { 

} 

public abstract class BaseContainer<T extends Item> { 
    public String getItemProperty(T item) { 
     return item.getValue(); 
    } 
} 

public class Document extends BaseContainer<WordItem> { 
} 

public static class ContainerFactory { 
    public static BaseContainer<? extends Item> getContainer(Item item) { 
    return new GenericTest().new Document(); 
    } 
} 

@Test 
public void theTest(){ 
    Item item = new WordItem(); 
    BaseContainer<? extends Item> container = ContainerFactory.getContainer(item); 
    String str = container.getItemProperty(item); //this line does not compile 
} 
} 

I'm。

+2

什么是编译器给你的错误? – KLee1 2010-07-21 16:17:04

+0

请在此问题中添加更多信息。或者它有被关闭的危险。 – jjnguy 2010-07-21 16:22:28

+0

这是编译器错误 方法getItemProperty(捕获#2的?延伸GenericTest.Item)在GenericTest.BaseContainer <捕获#2的类型?扩展GenericTest.Item>是不适用的参数(GenericTest.Item)使用Eclipse赫利俄斯与JDK 1.6.0_16 – Alex 2010-07-21 16:25:38

回答

1

为了摆脱错误的,你的代码更改为:

public static class ContainerFactory { 
    public static <T extends Item>BaseContainer<T> getContainer(Item item) { 
    return (BaseContainer<T>) new GenericTest().new Document(); 
    } 
} 

@Test 
public void theTest(){ 
    Item item = new WordItem(); 
    BaseContainer<Item> container = ContainerFactory.getContainer(item); 
    String str = container.getItemProperty(item); 
} 
+0

非常感谢 I'm ...奏效 – Alex 2010-07-21 16:38:20

2

我认为这个问题是containerBaseContainer<? extends Item>,即它是一些亚型Item的容器。然而,编译器无法确保有问题的亚型实际上Item本身的方式。而事实上,这是WordItem,不Item。总体问题是您的通用参数用法不一致并且不完整。

我可以让你的代码编译这些修改:

public class Document<T extends Item> extends BaseContainer<T> { 
} 

public static class ContainerFactory { 
    public static <T extends Item> BaseContainer<T> getContainer(T item) { 
    return new Test().new Document<T>(); 
    } 
} 

@Test 
public void theTest(){ 
    WordItem item = new WordItem(); 
    BaseContainer<WordItem> container = ContainerFactory.getContainer(item); 
    String str = container.getItemProperty(item); 
} 

这不同于TrueSoft的建议在这里Document也由一般 - 这可能不是你想要的(你给对此没有资料) ,但至少这种方式有内getContainer()不需要不安全的演员。