package main.java;

import jvm.VarHandleDemo;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

public class VarHandlerDemoRunner {

    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
        VarHandleDemo instance = new VarHandleDemo();

        //access private field
        VarHandle varHandle = MethodHandles
                .privateLookupIn(VarHandleDemo.class, MethodHandles.lookup())
                .findVarHandle(VarHandleDemo.class, "privateVar", int.class);
        varHandle.set(instance, 33);
        System.out.println(instance);

        //access protected field
        VarHandle varHandle2 = MethodHandles
                .privateLookupIn(VarHandleDemo.class,MethodHandles.lookup())
                .findVarHandle(VarHandleDemo.class, "protectedVar", int.class);
        varHandle2.set(instance, 22);
        System.out.println(instance);

        //access public field
        VarHandle varHandle3 = MethodHandles.lookup()
                .in(VarHandleDemo.class)
                .findVarHandle(VarHandleDemo.class, "publicVar", int.class);
        varHandle3.set(instance, 11);
        System.out.println(instance);

        //access array
        VarHandle varHandle4 = MethodHandles.arrayElementVarHandle(int[].class);
        varHandle4.compareAndSet(instance.publicArrayData, 0, 1,11);
        varHandle4.compareAndSet(instance.publicArrayData, 1, 2,22);
        varHandle4.compareAndSet(instance.publicArrayData, 2, 3,33);
        System.out.println(instance);
    }
}
