1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal.util.reflection;
6
7import java.lang.reflect.Field;
8import java.lang.reflect.Modifier;
9
10@SuppressWarnings("unchecked")
11public class LenientCopyTool {
12
13    FieldCopier fieldCopier = new FieldCopier();
14
15    public <T> void copyToMock(T from, T mock) {
16        copy(from, mock, from.getClass(), mock.getClass().getSuperclass());
17    }
18
19    public <T> void copyToRealObject(T from, T to) {
20        copy(from, to, from.getClass(), to.getClass());
21    }
22
23    private <T> void copy(T from, T to, Class fromClazz, Class toClass) {
24        while (fromClazz != Object.class) {
25            copyValues(from, to, fromClazz);
26            fromClazz = fromClazz.getSuperclass();
27        }
28    }
29
30    private <T> void copyValues(T from, T mock, Class classFrom) {
31        Field[] fields = classFrom.getDeclaredFields();
32
33        for (int i = 0; i < fields.length; i++) {
34            // ignore static fields
35            Field field = fields[i];
36            if (Modifier.isStatic(field.getModifiers())) {
37                continue;
38            }
39            AccessibilityChanger accessibilityChanger = new AccessibilityChanger();
40            try {
41                accessibilityChanger.enableAccess(field);
42                fieldCopier.copyValue(from, mock, field);
43            } catch (Throwable t) {
44                //Ignore - be lenient - if some field cannot be copied then let's be it
45            } finally {
46                accessibilityChanger.safelyDisableAccess(field);
47            }
48        }
49    }
50}