| |
|
Can you define something about Variable Handles in Java with example? Question Posted on 08 Aug 2021 Home >> Java >> Java Questions >> Can you define something about Variable Handles in Java with example? |
Can you define something about Variable Handles in Java with example?
Variable Handles is nothing but a variable or we can say its a reference to a set of variables. And variable handle is just a typed reference to a variable. The variable can be an instance, array element or static field of the class. And this will include other components of a non-static fields, static field and outer array elements in the heap data structure. This will also means that Variable Handle is similar to the existing Method Handle. And to represent this we use java.lang.invoke.VarHandle class. And we will use java.lang.invoke.MethodHandles.Lookup static factory method to create Variable Handle objects. And we can also used single element in the array, and byte[] array
to access. The VarHandle class provides write and read access to variables under specific conditions. VarHandles are immutable and have no visible state.
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Arrays;
public class VarHandleTest
{
public static void main(String args[])
{
VarHandle varTestHandle = MethodHandles.arrayElementVarHandle(int[].class);
int[] arrayTest = new int[5];
printArray(arrayTest);
varTestHandle.set(arrayTest, 2, 5);
printArray(arrayTest);
System.out.println(varTestHandle.get(arrayTest, 2));
}
private static void printArray(int[] arrayTest)
{
System.out.println(Arrays.toString(arrayTest));
}
}
| |
|
|
|
|