From e5363455564ba432d4f14d7f94a1e6cb31fb4fc7 Mon Sep 17 00:00:00 2001 From: Kam Date: Mon, 11 Mar 2024 16:34:27 -0400 Subject: [PATCH] Size of without Instrucmentation --- .../noppes/npcs/util/SizeOfObjectUtil.java | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/src/main/java/noppes/npcs/util/SizeOfObjectUtil.java b/src/main/java/noppes/npcs/util/SizeOfObjectUtil.java index 6d87f6fc8..55984b480 100644 --- a/src/main/java/noppes/npcs/util/SizeOfObjectUtil.java +++ b/src/main/java/noppes/npcs/util/SizeOfObjectUtil.java @@ -1,18 +1,35 @@ package noppes.npcs.util; import java.lang.instrument.Instrumentation; +import java.lang.reflect.Field; public class SizeOfObjectUtil { - private static volatile Instrumentation instrumentation; - - public static void initializeInstrumentation(Instrumentation inst) { - instrumentation = inst; - } - public static long sizeOfObject(Object obj) { - if (instrumentation == null) { - throw new IllegalStateException("Instrumentation is not initialized"); + long size = 0; + for (Field field : obj.getClass().getDeclaredFields()) { + try { + field.setAccessible(true); + Class type = field.getType(); + if (type == int.class || type == Integer.class) { + size += Integer.BYTES; + } else if (type == long.class || type == Long.class) { + size += Long.BYTES; + } else if (type == byte.class || type == Byte.class) { + size += Byte.BYTES; + } else if (type == boolean.class || type == Boolean.class) { + size += 1; // Assuming 1 byte for boolean + } // Add more cases for other primitive types if needed + else { + // If it's a reference type, recursively calculate its size + Object value = field.get(obj); + if (value != null) { + size += sizeOfObject(value); + } + } + } catch (IllegalAccessException e) { + // Handle exception + } } - return instrumentation.getObjectSize(obj); + return size; } }