在我看来,在这种情况下使用注释有点过度工程(你必须编写一个注释处理器)。您可以轻松地使用泛型和lambda和/或方法引用来实现您的目标。例如:
PartitionArray
以这种方式更新:
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
public class PartitionArray {
private static <T> Collection<List<T>> partitionBasedOnSize(List<T> inputList, int partitionSize) {
Collection<List<T>> collection = new ArrayList<>();
int remainingSize = inputList.size();
int index = 0;
while (remainingSize > partitionSize) {
collection.add(inputList.subList(index, index + partitionSize));
remainingSize -= partitionSize;
index += partitionSize;
}
collection.add(inputList.subList(index, index + remainingSize));
return collection;
}
public static <D, T> List<D> partitionAndDoBusinessFunction(List<T> ids, Function<List<T>, List<D>> businessFunction, int partitionSize) {
List<D> dataList = new ArrayList<>();
Collection<List<T>> idListCollection = partitionBasedOnSize(ids, partitionSize);
for (List<T> idList : idListCollection) {
dataList.addAll(businessFunction.apply(idList));
}
return dataList;
}
}
然后只需从您的AccountService
(使用方法参考)中使用它:
import java.util.List;
public class AccountService {
private AccountRepository accountRepository;
public List<Account> getAccounts(List<Long> ids) {
return PartitionArray.partitionAndDoBusinessFunction(ids, accountRepository::getAccounts, 30000);
}
}
或使用 lambda:
import java.util.List;
public class AccountService {
private AccountRepository accountRepository;
public List<Account> getAccounts(List<Long> ids) {
return PartitionArray.partitionAndDoBusinessFunction(ids, idList -> {
List<Account> accounts = accountRepository.getAccounts(idList);
// do more business on accounts
return accounts;
}, 30000);
}
}