• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.annotations;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 import static org.junit.Assert.assertThrows;
21 
22 import androidx.test.filters.SmallTest;
23 
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26 import org.junit.runners.JUnit4;
27 
28 import java.lang.ref.WeakReference;
29 import java.util.ArrayList;
30 import java.util.List;
31 
32 @RunWith(JUnit4.class)
33 @SmallTest
34 public class WeaklyReferencedCallbackTest {
35     @Test
testAnnotatedCallbackMemberKept()36     public void testAnnotatedCallbackMemberKept() throws Exception {
37         // Note: This code is simply to exercise the class behavior to ensure
38         // that it's kept during compilation.
39         List<WeakReference<Object>> weakRefs = new ArrayList<>();
40         ClassWithWeaklyReferencedCallback instance =
41                 new ClassWithWeaklyReferencedCallback(weakRefs);
42 
43         // Ensure fields of annotated callback types are kept.
44         // Note: We use an intermediate string field variable to avoid R8 using the reflection
45         // call itself (with the string constant) as an implicit Keep signal.
46         String[] keptFields = {"mKeptCallback"};
47         for (String field : keptFields) {
48             assertThat(instance.getClass().getDeclaredField(field)).isNotNull();
49         }
50         String[] strippedFields = {"mStrippedCallback"};
51         for (String field : strippedFields) {
52             assertThrows(
53                     NoSuchFieldException.class, () -> instance.getClass().getDeclaredField(field));
54         }
55     }
56 }
57