简体   繁体   English

使用lambda表达式将Java类作为函数参数

[英]Java class as a function parameter using lambda expressions

I have JUnit tests (which I cannot modify) and have to write a program in Java 8. The part of the tests that I'm interested in is: 我有JUnit测试(无法修改),并且必须用Java 8编写程序。我感兴趣的部分测试是:

Set<Customer> mexicans = shop.filter(Customer.class, c -> c.getCountry().equals("Mexico"));
Set<Product> goldenWaffles = shop.filter(Product.class, p -> p.getBrand().equals("Golden") && p.getName().contains("Waffles"));

So the second parameter of filter function is lambda expression, which I would take as parameter of type Predicate<Product> or Predicate<Customer> (am I right here?). 因此, 过滤器函数的第二个参数是lambda表达式,我将其作为Predicate<Product>Predicate<Customer>类型的参数(我在这里吗?)。 The problem is: I need to be able to take them both and I don't know how to do it. 问题是:我必须能够同时接受它们,而且我不知道该怎么做。 Has it something to do with the first parameter? 与第一个参数有关吗?

Probably you are looking for something like 可能您正在寻找类似的东西

public <T> void method(Class<T> clazz, Predicate<T> predicate) {
    // ...
    final Set<T> result = shop.filter(clazz, predicate);
}

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

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