mirror of
https://github.com/Kingsrook/qqq.git
synced 2025-07-18 13:10:44 +00:00
Add ifCan utility method
This commit is contained in:
@ -139,4 +139,28 @@ public class ObjectUtils
|
||||
return (b);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Utility to test a chained unsafe expression CAN get to the end and return true.
|
||||
**
|
||||
** e.g., instead of:
|
||||
** if(a && a.b && a.b.c && a.b.c.d)
|
||||
** we can do:
|
||||
** if(ifCan(() -> a.b.c.d))
|
||||
**
|
||||
** Note - if the supplier returns null, that counts as false!
|
||||
*******************************************************************************/
|
||||
public static boolean ifCan(UnsafeSupplier<Boolean, ? extends Throwable> supplier)
|
||||
{
|
||||
try
|
||||
{
|
||||
return supplier.get();
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -25,7 +25,9 @@ package com.kingsrook.qqq.backend.core.utils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
@ -79,4 +81,20 @@ class ObjectUtilsTest
|
||||
assertEquals("else", ObjectUtils.tryAndRequireNonNullElse(() -> null, "else"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testIfCan()
|
||||
{
|
||||
Object nullObject = null;
|
||||
assertTrue(ObjectUtils.ifCan(() -> true));
|
||||
assertTrue(ObjectUtils.ifCan(() -> "a".equals("a")));
|
||||
assertFalse(ObjectUtils.ifCan(() -> 1 == 2));
|
||||
assertFalse(ObjectUtils.ifCan(() -> nullObject.equals("a")));
|
||||
assertFalse(ObjectUtils.ifCan(() -> null));
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user