Added ObjectUtil class
This commit is contained in:
parent
beb0ce754e
commit
501fbf1a5f
2 changed files with 56 additions and 0 deletions
27
src/zutil/ObjectUtil.java
Normal file
27
src/zutil/ObjectUtil.java
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
package zutil;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A utility class containing general object functions
|
||||||
|
*/
|
||||||
|
public class ObjectUtil {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return true if obj is null or empty String, List, Map
|
||||||
|
*/
|
||||||
|
public static boolean isEmpty(Object obj) {
|
||||||
|
if (obj == null)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (obj instanceof Map)
|
||||||
|
return ((Map) obj).isEmpty();
|
||||||
|
else if (obj instanceof List)
|
||||||
|
return ((List) obj).isEmpty();
|
||||||
|
else if (obj instanceof CharSequence)
|
||||||
|
return ((CharSequence) obj).length() == 0;
|
||||||
|
|
||||||
|
return false; // We don't know the type of class, but it is not null
|
||||||
|
}
|
||||||
|
}
|
||||||
29
test/zutil/ObjectUtilTest.java
Normal file
29
test/zutil/ObjectUtilTest.java
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
package zutil;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class ObjectUtilTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void isEmpty() {
|
||||||
|
assertTrue(ObjectUtil.isEmpty(null));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(""));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(new StringBuffer()));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(new StringBuilder()));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(new ArrayList<>()));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(new LinkedList<>()));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(new HashMap<>()));
|
||||||
|
assertTrue(ObjectUtil.isEmpty(new Hashtable<>()));
|
||||||
|
|
||||||
|
|
||||||
|
assertFalse(ObjectUtil.isEmpty(" "));
|
||||||
|
assertFalse(ObjectUtil.isEmpty("a"));
|
||||||
|
assertFalse(ObjectUtil.isEmpty(new StringBuilder("a")));
|
||||||
|
assertFalse(ObjectUtil.isEmpty(new StringBuffer("a")));
|
||||||
|
assertFalse(ObjectUtil.isEmpty(Arrays.asList(1, 2, 3)));
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue