blob: 231ee6a94cf0557c4aa76822b338694d00aa0c13 [file] [log] [blame]
Søren Gjesse6f80c1a2022-11-30 17:13:05 +01001// Copyright (c) 2022, the R8 project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4package varhandle;
5
6import java.lang.invoke.MethodHandles;
7import java.lang.invoke.VarHandle;
8
9public class InstanceStringField {
10
11 private Object field;
12
13 private static void println(String s) {
14 System.out.println(s);
15 }
16
Søren Gjesseca343fd2022-12-20 16:22:00 +010017 public static void testGet(VarHandle varHandle) {
Søren Gjesse6f80c1a2022-11-30 17:13:05 +010018 System.out.println("testGet");
19
20 InstanceStringField instance = new InstanceStringField();
21
22 // Then polymorphic invoke will remove the cast and make that as the return type of the get.
Søren Gjesseca343fd2022-12-20 16:22:00 +010023 System.out.println((String) varHandle.get(instance));
24 varHandle.set(instance, "1");
25 System.out.println(varHandle.get(instance));
26 System.out.println((Object) varHandle.get(instance));
27 System.out.println((String) varHandle.get(instance));
28 System.out.println((CharSequence) varHandle.get(instance));
29 try {
30 System.out.println((Byte) varHandle.get(instance));
31 System.out.println("Unexpected success");
32 } catch (ClassCastException e) {
33 }
34 }
35
36 public static void testSet(VarHandle varHandle) {
37 System.out.println("testSet");
38
39 InstanceStringField instance = new InstanceStringField();
40
41 // Then polymorphic invoke will remove the cast and make that as the return type of the get.
Søren Gjesse6f80c1a2022-11-30 17:13:05 +010042 println((String) varHandle.get(instance));
43 varHandle.set(instance, "1");
44 println((String) varHandle.get(instance));
45 }
46
47 public static void testCompareAndSet(VarHandle varHandle) {
48 System.out.println("testCompareAndSet");
49
50 InstanceStringField instance = new InstanceStringField();
51
52 varHandle.compareAndSet(instance, 0, "1");
53 println((String) varHandle.get(instance));
54 varHandle.compareAndSet(instance, null, "1");
55 println((String) varHandle.get(instance));
56 }
57
58 public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
59 VarHandle varHandle =
60 MethodHandles.lookup().findVarHandle(InstanceStringField.class, "field", Object.class);
Søren Gjesseca343fd2022-12-20 16:22:00 +010061 testGet(varHandle);
Søren Gjesse6f80c1a2022-11-30 17:13:05 +010062 testSet(varHandle);
63 testCompareAndSet(varHandle);
64 }
65}