ObjectUtils.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
memoizeit /
utils /
ObjectUtils.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ufrgs.inf.prosoft.memoizeit.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* @author romulo
*/
public class ObjectUtils {
public static Object truncateObject(Object object, int depth, Action onTruncate) {
if (depth == 0) {
onTruncate.perform();
return "...";
}
if (object instanceof Map) {
Map<String, Object> map = (Map<String, Object>) object;
map.entrySet().forEach((entry) -> {
entry.setValue(truncateObject(entry.getValue(), depth - 1));
});
} else if (object instanceof List) {
List list = (List) object;
for (int i = 0; i < list.size(); i++) {
list.set(i, truncateObject(list.get(i), depth - 1));
}
}
return object;
}
public static Object truncateObject(Object object, int depth) {
return truncateObject(object, depth, () -> {
});
}
public static List<Object> deepCopy(List<Object> object) {
List<Object> collection = new ArrayList<>();
object.forEach((item) -> {
collection.add(deepCopy(item));
});
return collection;
}
public static Object deepCopy(Object object) {
try {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
objectOutputStream.writeObject(object);
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
return objectInputStream.readObject();
}
}
} catch (IOException | ClassNotFoundException ex) {
System.err.println("[MemoizeIt] clone exception: " + ex);
return null;
}
}
}