ObjectUtils.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
memoizeit /
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;
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.Collection;
import java.util.List;
import java.util.Map;
/**
*
* @author romulo
*/
public class ObjectUtils {
public static Object truncateObject(Object object, int depth) {
if (depth == 0) {
object = "...";
}
if (object instanceof Map) {
Map<String, Object> map = (Map<String, Object>) object;
map.entrySet().forEach((entry) -> {
truncateObject(entry.getValue(), depth - 1);
});
} else if (object instanceof Collection) {
Collection collection = (Collection) object;
collection.forEach((item) -> {
truncateObject(item, depth - 1);
});
}
return object;
}
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;
}
}
}