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 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 KeepForWeakReferenceTest { 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 assertThat(instance.getClass().getDeclaredField(field)).isNotNull(); 48 } 49 String[] strippedFields = {"mStrippedField"}; 50 for (String field : strippedFields) { 51 assertThrows( 52 NoSuchFieldException.class, () -> instance.getClass().getDeclaredField(field)); 53 } 54 } 55 } 56