强制一个泛型类型是一个接口? [英] Force a generic type to be an interface?

查看:115
本文介绍了强制一个泛型类型是一个接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来这是不可能做到的,但是有没有人有解决这个问题的巧妙方法?

  public class SomeClassIterableWrapper< ; S,T延伸SomeClass& S>实现了Iterable< S> 

其中 S 应该是一个界面某些未知类型和 SomeClass 是一个具有行索引的二维数组,其功能与双向JDBC结果集类似。 SomeClass 的子类对每列都有自定义的getter和setter。我希望能够遍历这个结构,就像我会List一样。我想在我的 SomeClass 和Bean之间实现一个通用接口以访问getters和setter。因此S需要成为那个界面。但是我提供的声明不起作用。有没有办法解决这个问题?



编辑显示我想要的实现:

  public class SomeClassIterableWrapper< S,T extends SomeClass& S>实现Iterable< S> {

T object;

public SomeClassWrapper(T object){
this.object = object;
}

@Override
public Iterator< S> iterator(){
object.setIndex(-1);
返回新SomeClassIterator< S>();
}

private class SomeClassIterator< S>实现Iterator< S> {

@Override
public boolean hasNext(){
return object.index()< object.rowSize() - 1;
}

@Override
public S next(){
object.next();
//安全,因为只有接口方法允许,不能进一步操作索引
返回对象;
}

@Override
public void remove(){
object.deleteRow();
}
}


解决方案

Can你用 S 来参数化 SomeClass ?然后你可以有

pre $ public class SomeClassIterableWrapper< S,T extends SomeClass< S>>
实现了Iterable< S> {


It looks like this is impossible to do, but does anyone have a clever way around this problem?

public class SomeClassIterableWrapper<S, T extends SomeClass & S> implements Iterable<S>

Where S is supposed to be an interface of some unknown type and SomeClass is a 2D array with a row index, similar in functionality to a bidirectional JDBC resultset. Subclasses of SomeClass have custom getters and setters for each column. I want to be able to iterate through this structure like I would a List. I want to implement a common interface between my SomeClass and Bean to have access to the getters and setters. As such S needs to be that interface. However the declaration I provided does not work. Is there a way to work around this?

edit to show my desired implementation:

public class SomeClassIterableWrapper<S, T extends SomeClass & S> implements Iterable<S>{

T object;

public SomeClassWrapper(T object){
    this.object = object;
}

@Override
public Iterator<S> iterator() {
    object.setIndex(-1);
    return new SomeClassIterator<S>();
}

private class SomeClassIterator<S> implements Iterator<S> {

    @Override
    public boolean hasNext() {
        return object.index() < object.rowSize() - 1;
    }

    @Override
    public S next() {
        object.next();
        //safe because only interface methods allowed, can't further manipulate index
        return object; 
    }

    @Override
    public void remove() {
        object.deleteRow();
    }
}

解决方案

Can't you parameterize SomeClass with S? Then you could have

public class SomeClassIterableWrapper<S, T extends SomeClass<S>> 
      implements Iterable<S>{

这篇关于强制一个泛型类型是一个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆