繁体   English   中英

参数类型?

[英]Types by argument?

我想知道是否可能通过Java中的参数传递类型。

让我解释一下:

假设下一个代码

class Bee {
    // Class implementation
}

class Worker extends Bee {
    // Class implementation
}


class Queen extends Bee {
    // Class implementation
}

现在用蜜蜂对象创建一个容器

Vector<Bee> x=new Vector<Bee>();
// ...
for(i=0;i<10;i++)
    x.add(new Worker());
// ...
for(i=0;i<10;i++)
    x.add(new Queen());

现在我想创建一个泛型方法来迭代向量并返回一个具有特定类型的蜜蜂,工人或女王的集合。 这个怎么做?

编辑

我试过了

search(x,Worker.class);

static public <T extends Bee> Set<T> search(List<Bee> bees, Class<T> clazz){
    // ...
}

我收到错误报告“方法搜索(List,Class)不适用于参数(Set,Class)”。 问题出在第二个参数上,因为类型不兼容。

您可以使用instanceof表达式来测试BeeWorker还是Queen 您可以根据子类型使用它来过滤Vector<Bee> (甚至更好, List<Bee> )。

Guava还提供了可以使用的Iterables.filter(Iterable<?> unfiltered, Class<T> type)

从我的编辑中我看到,你仍然在努力实施。 这是一个工作示例:

public static void main(String[] args) {
    Collection<Bee> bees = new ArrayList<Bee>();
    bees.add(new Hive.Worker());
    bees.add(new Hive.Queen());
    Set<Queen> queens = getBeesOfOneType(bees, Queen.class);
}

private static <T extends Bee> Set<T> getBeesOfOneType(Collection<Bee> bees, Class<T> beeType) {
    Set<T> result = new HashSet<T>();
    for (Bee bee : bees) {
        if (beeType.isInstance(bee)) {
            // The following cast is safe. The previous if makes sure that
            // that bee can be cast to T at this place
            T beeTypeInstance = beeType.cast(bee);
            result.add(beeTypeInstance);
        }
    }
    return result;
}

还有一个类型安全警告,我很确定这个不能被消除。 编译器现在没有,我们只选择T型蜜蜂,所以它必须警告我们。

使用Class作为方法的参数

public <T extends Bee> Set<T> filterBeesByType(List<Bee> bees, Class<T> clazz)

顺便说一下,通过它们的接口( SetList等)而不是实现( Vector )来引用集合类型是一个好习惯。

使用instanceof运算符:

public static Set<Queen> queensOnly(Collection<Bee> bees) {
  Set<Queen> queens = new HashSet<Queen>();
  for (Bee bee:bees) {
    if (bee instanceof Queen) {
      queens.add((Queen) bee);
    }
  }
  return queens;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM