1 /*
2  * Copyright (C) 2021 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.launcher3.util;
18 
19 import java.lang.reflect.Field;
20 
21 public class ReflectionHelpers {
22 
23     /**
24      * Reflectively get the value of a field.
25      *
26      * @param object Target object.
27      * @param fieldName The field name.
28      * @param <R> The return type.
29      * @return Value of the field on the object.
30      */
getField(Object object, String fieldName)31     public static <R> R getField(Object object, String fieldName) {
32         try {
33             Field field = object.getClass().getDeclaredField(fieldName);
34             field.setAccessible(true);
35             return (R) field.get(object);
36         } catch (Exception e) {
37             throw new RuntimeException(e);
38         }
39     }
40 
41     /**
42      * Reflectively set the value of a field.
43      *
44      * @param object Target object.
45      * @param fieldName The field name.
46      * @param fieldNewValue New value.
47      */
setField(Object object, String fieldName, Object fieldNewValue)48     public static void setField(Object object, String fieldName, Object fieldNewValue) {
49         try {
50             Field field = object.getClass().getDeclaredField(fieldName);
51             field.setAccessible(true);
52             field.set(object, fieldNewValue);
53         } catch (Exception e) {
54             throw new RuntimeException(e);
55         }
56     }
57 
58 }
59