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