简体   繁体   English

Java中的泛型生产者和消费者

[英]Producer and Consumer with Generics in Java

I have this method to retrieve the objects which are instance of a given class: 我有这个方法来检索作为给定类的实例的对象:

public class UtilitiesClass {

    public static final Collection<Animal> get(Collection<Animal> animals, Class<? extends Animal> clazz) {
        // returns the Animals which are an instanceof clazz in animals
    }
...
}

To call the method, I can do something like this: 要调用该方法,我可以这样做:

Collection<Animal> dogs = UtilitiesClass.get(animals, Dog.class);

That is good, but I would also like to be able to call the method in these two ways: 这很好,但我也希望能够通过以下两种方式调用该方法:

Collection<Animal> dogs = UtilitiesClass.get(animals, Dog.class);

or 要么

Collection<Dog> dogsTyped = UtilitiesClass.get(animals, Dog.class);

What I mean is that I want to be able to store result of the method in a Dog Collection or in an Animal one, because Dog.class extends Animal.class 我的意思是我希望能够将方法的结果存储在Dog Collection或Animal中,因为Dog.class扩展了Animal.class

I was thinking in something like this: 我在考虑这样的事情:

public static final <T> Collection<T> get(Class<T extends Animal> clazz) {
    // returns the Animals which are an instanceof clazz
}

But it does not work. 但它不起作用。 Any hint? 任何提示?

Edit: Finally, using @Rohit Jain answer, this is the solution when you call to the UtilitiesClass method: 编辑:最后,使用@Rohit Jain答案,这是调用UtilitiesClass方法时的解决方案:

Collection<? extends Animal> dogsAnimals = UtilitiesClass.get(animals, Dog.class);
Collection<Dog> dogs = UtilitiesClass.get(animals, Dog.class);

Yes, you have to make the method generic. 是的,你必须使方法通用。 And the bounds should be given while declaring the type parameter: 并且在声明类型参数时应该给出界限:

public static final <T extends Animal> Collection<T> get(
                   Collection<Animal> animals, Class<T> clazz) {
}

But, while adding the animal from animals collection to a new Collection<T> , you would have to cast it back to clazz type. 但是,在将animals集合中的animal添加到新的Collection<T> ,您必须将其转换为clazz类型。 You would need Class#isInstance(Object) method, and also Class#cast(Object) method. 您将需要Class#isInstance(Object)方法,以及Class#cast(Object)方法。

This is possible in Java 8 without using Class<T> , however still may involve typecasting. 这可以在Java 8中使用而不使用Class<T> ,但是仍然可能涉及类型转换。 A version that does not involve typecasting is also possible, but a bit more verbose: 一个不涉及类型转换的版本也是可能的,但有点冗长:

public interface Animal {
    public void makeSound();
}

public class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Waf");
    }
}

public class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Miauw");
    }
}

public abstract class Utils {
    @SuppressWarnings("unchecked")
    public static <T_IN, T_OUT> Collection<T_OUT> getBySubType(Collection<T_IN> input, Predicate<T_IN> predicate) {
        return input.stream()
                .filter(predicate)
                .map(element -> (T_OUT)element)
                .collect(Collectors.toList());
    }

    public static <T_IN, T_OUT> Collection<T_OUT> getBySubTypeSafe(Collection<T_IN> input, Predicate<T_IN> predicate, Function<T_IN, T_OUT> function) {
        return input.stream()
                .filter(predicate)
                .map(function)
                .collect(Collectors.toList());
    }
}

public class TestProject3 {
    private void init() {
        List<Animal> animals = new ArrayList<>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Dog());
        animals.add(new Cat());
        animals.forEach(Animal::makeSound);

        System.out.println();

        Collection<Dog> dogs = Utils.getBySubType(animals, animal -> (animal instanceof Dog));
        dogs.forEach(Animal::makeSound);

        System.out.println();

        Collection<Cat> cats = Utils.getBySubTypeSafe(animals, animal -> (animal instanceof Cat), animal -> (Cat)animal);
        cats.forEach(Animal::makeSound);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new TestProject3().init();
    }
}

Output: 输出:

Waf WAF
Miauw Miauw
Waf WAF
Miauw Miauw

Waf WAF
Waf WAF

Miauw Miauw
Miauw Miauw

What it does, is, in getBySubType resp getBySubTypeSafe : 它的作用是,在getBySubType resp中getBySubTypeSafe

  • Obtain as input Collection<T_IN> . 获取输入Collection<T_IN>
  • Filter everything based on the instanceof predicate. 根据谓词的instanceof过滤所有内容。
  • In one version cast it to T_OUT , in our version use a Function<T_IN, T_OUT> to explicitely safely cast it. 在一个版本T_OUT其转换为T_OUT ,在我们的版本中使用Function<T_IN, T_OUT>来明确地安全地转换它。
  • Return the Collection<T_OUT> . 返回Collection<T_OUT>

The argument type should be generic wildcard to accept input collections of any subclass of Animal. 参数类型应该是通用通配符,以接受Animal的任何子类的输入集合。

public static final <T extends Animal> Collection<T> get(
        Collection<? extends Animal> animals, Class<T> clazz ) {
    Collection<T> filteredAnimals = new ArrayList<T>();
    for ( Animal animal : animals ) {
        if ( clazz.isInstance( animal ) ) {
            filteredAnimals.add( clazz.cast( animal ) );
        }
    }
    return filteredAnimals;
}

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

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