SerializeUtils.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.nuliji.tools.shiro;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.*;
  5. /**
  6. * Created by gaojie on 2017/11/7.
  7. */
  8. public class SerializeUtils {
  9. private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class);
  10. /**
  11. * 反序列化
  12. * @param bytes
  13. * @return
  14. */
  15. public static Object deserialize(byte[] bytes) {
  16. Object result = null;
  17. if (isEmpty(bytes)) {
  18. return null;
  19. }
  20. try {
  21. ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
  22. try {
  23. ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
  24. try {
  25. result = objectInputStream.readObject();
  26. }
  27. catch (ClassNotFoundException ex) {
  28. throw new Exception("Failed to deserialize object type", ex);
  29. }
  30. }
  31. catch (Throwable ex) {
  32. throw new Exception("Failed to deserialize", ex);
  33. }
  34. } catch (Exception e) {
  35. logger.error("Failed to deserialize",e);
  36. }
  37. return result;
  38. }
  39. public static boolean isEmpty(byte[] data) {
  40. return (data == null || data.length == 0);
  41. }
  42. /**
  43. * 序列化
  44. * @param object
  45. * @return
  46. */
  47. public static byte[] serialize(Object object) {
  48. byte[] result = null;
  49. if (object == null) {
  50. return new byte[0];
  51. }
  52. try {
  53. ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
  54. try {
  55. if (!(object instanceof Serializable)) {
  56. throw new IllegalArgumentException(SerializeUtils.class.getSimpleName() + " requires a Serializable payload " +
  57. "but received an object of type [" + object.getClass().getName() + "]");
  58. }
  59. ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
  60. objectOutputStream.writeObject(object);
  61. objectOutputStream.flush();
  62. result = byteStream.toByteArray();
  63. }
  64. catch (Throwable ex) {
  65. throw new Exception("Failed to serialize", ex);
  66. }
  67. } catch (Exception ex) {
  68. logger.error("Failed to serialize",ex);
  69. }
  70. return result;
  71. }
  72. }