Java Code Examples: Common Logic Processing

Multiple attempts to get the result

public class LogicProcessingUtils {
/**
* @param maxTryTimes
* @param successPredicate
* @param function
* @param params parameter object
* @param <T> function return type
* @param <P> function parameter type
* @return
*/
public static <T, P> T tryToGetResult(int maxTryTimes,
Predicate<T> successPredicate,
Function<P, T> function,
P param) {
int tryTimes = 0;
T t = null;
while (tryTimes < maxTryTimes) {
t = function.apply(param);
// System.out.println(t);
if (successPredicate.test(t)) {
break;
}
tryTimes++;
}
return t;
}

public static <T> T tryToGetResult(int maxTryTimes,
Predicate<T> successPredicate,
Supplier<T> supplier) {
int tryTimes = 0;
T t = null;
while (tryTimes < maxTryTimes) {
t = supplier.get();
// System.out.println(t);
if (successPredicate.test(t)) {
break;
}
tryTimes++;
}
return t;
}
}
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
int maxTryTimes = 3;
ObjectNode result = LogicProcessingUtils.tryToGetResult(
maxTryTimes,
jsonNode -> jsonNode.get("code").asInt() == 200,
myTest::getResult,
0);
System.out.println(result);
}

public ObjectNode getResult(Object param) {
System.out.println("param: " + param);
ThreadLocalRandom random = ThreadLocalRandom.current();
int randomNumber = random.nextInt(10);
System.out.println("random number: " + randomNumber);
String jsonStr = "{\"code\":500,\"data\":%d,\"msg\":\"请求失败\"}";
ObjectMapper objectMapper = new ObjectMapper();
try {
return (ObjectNode) objectMapper.readTree(String.format(jsonStr, randomNumber));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}