从一个obj传递到另一个obj的通用参数

时间:2012-04-16 05:42:03

标签: java generics design-patterns

我的情况是:ResourceService<T , ID >

中的保存方法
public interface IResourceService<T,ID>

public class ResourceService<T , ID> implement IResourceService<T,ID>
{
   public void save(T entity) throws RuntimeException {

    try {
        AsyncServiceSaveRunable<T> task = new
AsyncServiceSaveRunable<T>(getService(),entity);

        this.treadPoolExcutor.submitTask(task);
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


   }
}

并在

public class AsyncServiceSaveRunable<T> implements Runnable  {
private IResourceService<?,?> service; //----> this is 
private Method serviceMethod;
private List<T> parameters;

public AsyncServiceSaveRunable(IResourceService<?,?> service,  List<T> parameters){ 
}

public AsyncServiceSaveRunable(IResourceService<?,?> service, T parameter)
                            throws NoSuchMethodException, SecurityException{

    this.service         = service;

    this.parameters = new ArrayList<T>();
    this.parameters.add(parameter);
}
@Override
public void run() {
    try {
        if(this.parameters.size()>1)
            service.saveList(this.parameters);
        else
            service.save( this.parameters.get(0));
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  }
 }

问题是service.saveList(this.parameters);和service.save(...); 是错的

无论如何都要传递该参数 或者我需要一种不同的结构来处理这种情况?

谢谢

------------------来自eclipse的错误消息------------------------ < / p>

The method save(capture#7-of ?) in the type IResourceService<capture#7-of ?,capture#8-of ?>
 is not applicable for the arguments (T)

1 个答案:

答案 0 :(得分:4)

ResourceService<T extends BaseEntity, ...>中,您需要T BaseEntity {/ 1}}。

public class AsyncServiceSaveRunable<T> T中没有任何限制。

然后在service.save(this.parameters.get(0));中,您尝试将(无界)泛型类型传递给需要BaseEntity对象(或从中派生的对象)的函数。

您可以要求AsyncServiceSaveRunable的类型参数也来自BaseEntity:

public class AsyncServiceSaveRunable<T extends BaseEntity>

更新: 错误消息是IResourceService的第一个类型参数对save()所需的类型无效。以前,您使用BaseEntry限定的类型参数,但现在缺少此限制。也许你想写:IResourceService<? extends BaseEntity, ? extends Serializable>