-1

I used below code but i am getting the null pointer exception on using getObjectSize method

 import java.lang.instrument.Instrumentation;

    public class ObjectSizeFetcher {
        private static Instrumentation instrumentation;

        public static void premain(String args, Instrumentation inst) {
            instrumentation = inst;
        }

        public static long getObjectSize(Object o) {
            return instrumentation.getObjectSize(o);
        }
    }

public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}
Sandeep Kumar
  • 249
  • 3
  • 14

1 Answers1

1

It seems you newer call premain method so you never initialize the instrumentation field.

aussie
  • 119
  • 5
  • what parameters should i pass while calling premain() method – Sandeep Kumar May 03 '18 at 10:02
  • Well the parameters of the premain method are a string and an Instrumentation objects so you need to provide them.Since Instrumentation is an interface you will need something that implements it. For example you could use InstrumentationImpl. – aussie May 03 '18 at 10:17
  • i tried using InstrumentationImpl for creasting the object, but i am not able to create object since the constructor is private. – Sandeep Kumar May 04 '18 at 05:20
  • I also tried for creating my custom implementation of Instrumentation but i am getting the object size as null – Sandeep Kumar May 04 '18 at 05:21
  • Ah ok sorry i didn't realize it. Read more about instrumentation in the docs it explains how you can get an instance https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html – aussie May 04 '18 at 08:43