2016-05-12 35 views
0

为了让我的建设者到工厂(像):反射到建筑商和ArrayList

public Class<? extends ILink> getLinkImplClass(){ 
    return LinkJPA.class; 
} 

public LinkBuilder getLinkBuilder() throws BuilderException { 
    return new LinkBuilder(getLinkImplClass()); 
} 

我使用delegateBuilder:

public class DelegateBuilder<T> { 
private final Constructor<T> constructor; 

public DelegateBuilder(Class<? extends T> constructorClass, Class<?>[] expectedTypes) throws BuilderException { 
    try { 
     constructor = (Constructor<T>) constructorClass.getConstructor(expectedTypes); 
    } catch (NoSuchMethodException e) { 
     throw new BuilderException(e); 
    } 
} 

public T build(Object[] params) throws BuilderException { 
    try { 
     return constructor.newInstance(params); 
    } catch (Exception e) { 
     throw new BuilderException(e); 
    } 
} 
} 

它正常工作了好建设者,但是当我必须使用它不包含的通用列表。

这是我InventoryBuilder:

public class InventoryBuilder { 
    private DelegateBuilder<IInventory> delegateBuilder; 
    /** 
    * List of items to set to the inventory to build 
    */ 
    private List<IItem> items; 

    /** 
    * Public constructor of the InventoryBuilder 
    */ 
    public InventoryBuilder(Class<? extends IInventory> constructorClass) throws BuilderException { 
     items = new ArrayList<>(); 
     delegateBuilder = new DelegateBuilder<>(constructorClass, 
       new Class[]{items.getClass()}); 
    } 

    public InventoryBuilder addItems(List<IItem> items) 
    { 
     this.items.addAll(items); 
     return this; 
    } 

    public InventoryBuilder addItems(IItem ... items) 
    { 
     this.items.addAll(Arrays.asList(items)); 
     return this; 
    } 

    /** 
    * Function used to build the new Inventory 
    * 
    * @return 
    *    The new Inventory 
    */ 
    public IInventory build() throws BuilderException { 
     return delegateBuilder.build(new Object[]{items}); 
    } 
} 

(对不起,我没有找到如何正确地把以前的代码)

items.getClass()似乎是一个ArrayList而不是ArrayList<IITem>

有没有解决方案呢?

+0

您遇到的实际问题是什么?你有编译错误吗?某处是否抛出异常? – Radiodef

+0

解决方案可能是使用一些typetoken,请参阅https://github.com/google/guava/wiki/ReflectionExplained – 2016-05-12 16:11:39

+0

是的,该过程抛出一个错误: fr.univtln.procrastinateurs.m1.dapm.Utils.Builder .Exception.BuilderException:fr.univtln.procrastinateurs.m1.dapm.Entities.Inventory.InventoryJPA。 (java.lang.Object)当我试着用Object.class来代替。 –

回答

-1

该问题与type erasure有关。

基本上编译应用类型擦除到:

与他们的界限替换泛型类型的所有类型的参数或对象,如果类型参数是无限的。 T 他生成的字节码,因此只包含普通的类,接口和方法

+0

我已经尝试过Arraylist.class的Object.class instad,但它仍然无法工作。 –