1 /*
2  * Copyright (C) 2022 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 androidx.test.filters.SmallTest;
20 
21 import junit.framework.TestCase;
22 
23 import org.junit.Test;
24 import org.junit.runner.RunWith;
25 import org.junit.runners.JUnit4;
26 
27 import java.lang.ref.WeakReference;
28 import java.util.ArrayList;
29 import java.util.List;
30 
31 @RunWith(JUnit4.class)
32 @SmallTest
33 @Keep
34 public class KeepForWeakReferenceTest extends TestCase {
35     @Test
testAnnotatedMemberKept()36     public void testAnnotatedMemberKept() 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         ClassWithWeaklyReferencedField instance = new ClassWithWeaklyReferencedField(weakRefs);
41 
42         // Ensure annotated fields are kept.
43         // Note: We use an intermediate string field variable to avoid R8 using the reflection
44         // call itself (with the string constant) as an implicit Keep signal.
45         String[] keptFields = {"mKeptField"};
46         for (String field : keptFields) {
47             assertTrue(instance.getClass().getDeclaredField(field) != null);
48         }
49     }
50 }
51