Best Powermock code snippet using org.powermock.classloading.DeepCloner.performClone
Source:DeepCloner.java
...69 * @return A deep clone of the object to clone.70 */71 public <T> T clone(T objectToClone, boolean includeStandardJavaType) {72 assertObjectNotNull(objectToClone);73 return performClone(ClassLoaderUtil.loadClass(getType(objectToClone), targetCL), objectToClone,74 includeStandardJavaType);75 }76 @SuppressWarnings("unchecked")77 private static <T> Class<T> getType(T object) {78 if (object == null) {79 return null;80 }81 return (Class<T>) (object instanceof Class ? object : object.getClass());82 }83 private static boolean isClass(Object object) {84 if (object == null) {85 return false;86 }87 return object instanceof Class<?>;88 }89 private static void assertObjectNotNull(Object object) {90 if (object == null) {91 throw new IllegalArgumentException("Object to clone cannot be null");92 }93 }94 @SuppressWarnings("unchecked")95 private <T> T performClone(Class<T> targetClass, Object source, boolean shouldCloneStandardJavaTypes) {96 Object target = null;97 if (targetClass.isArray() && !isClass(source)) {98 return (T) instantiateArray(targetCL, targetClass, source, shouldCloneStandardJavaTypes);99 } else if (isJavaReflectMethod(targetClass)) {100 return (T) cloneJavaReflectMethod(source);101 } else if (targetClass.isPrimitive() || isSunClass(targetClass) || isJavaReflectClass(targetClass)) {102 return (T) source;103 } else if (isSerializableCandidate(targetClass, source)) {104 return (T) serializationClone(source);105 } else if (targetClass.isEnum()) {106 return (T) cloneEnum(targetCL, source);107 } else if (isClass(source)) {108 return (T) ClassLoaderUtil.loadClass(getType(source), targetCL);109 } else {110 target = isClass(source) ? source : Whitebox.newInstance(targetClass);111 }112 if (target != null) {113 referenceMap.put(source, target);114 cloneFields(targetCL, targetClass, source, target, referenceMap, shouldCloneStandardJavaTypes);115 }116 return (T) target;117 }118 private Object cloneJavaReflectMethod(Object source) {119 Method sourceMethod = (Method) source;120 Class<?> declaringClass = sourceMethod.getDeclaringClass();121 Class<?> targetClassLoadedWithTargetCL = ClassLoaderUtil.loadClass(declaringClass, targetCL);122 Method targetMethod = null;123 try {124 targetMethod = targetClassLoadedWithTargetCL.getDeclaredMethod(sourceMethod.getName(),125 sourceMethod.getParameterTypes());126 } catch (Exception e) {127 SafeExceptionRethrower.safeRethrow(e);128 }129 if (sourceMethod.isAccessible()) {130 targetMethod.setAccessible(true);131 }132 return targetMethod;133 }134 private boolean isJavaReflectMethod(Class<?> cls) {135 return cls.getName().equals(Method.class.getName());136 }137 private boolean isSunClass(Class<?> cls) {138 return cls.getName().startsWith("sun.");139 }140 private boolean isJavaReflectClass(Class<?> cls) {141 return cls.getName().startsWith("java.lang.reflect");142 }143 private <T> boolean isSerializableCandidate(Class<T> targetClass, Object source) {144 return isStandardJavaType(targetClass)145 && (isSerializable(targetClass) || isImpliticlySerializable(targetClass))146 && !Map.class.isAssignableFrom(source.getClass())147 && !Iterable.class.isAssignableFrom(source.getClass());148 }149 private static boolean isImpliticlySerializable(Class<?> cls) {150 return cls.isPrimitive();151 }152 private static boolean isSerializable(Class<?> cls) {153 return Serializable.class.isAssignableFrom(cls);154 }155 /*156 * Perform simple serialization157 */158 private Object serializationClone(Object source) {159 ObjectOutputStream oos = null;160 ObjectInputStream ois = null;161 try {162 ByteArrayOutputStream bos = new ByteArrayOutputStream();163 oos = new ObjectOutputStream(bos);164 oos.writeObject(source);165 oos.flush();166 ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());167 ois = new ObjectInputStream(bin);168 return ois.readObject();169 } catch (Exception e) {170 throw new RuntimeException(e);171 } finally {172 close(oos);173 close(ois);174 }175 }176 private void close(Closeable closeable) {177 try {178 if (closeable != null) {179 closeable.close();180 }181 } catch (IOException e) {182 }183 }184 @SuppressWarnings({ "unchecked", "rawtypes" })185 private Object cloneEnum(ClassLoader targetCL, Object source) {186 Object target;187 final Class enumClassLoadedByTargetCL = ClassLoaderUtil.loadClass(getType(source), targetCL);188 target = getEnumValue(source, enumClassLoadedByTargetCL);189 return target;190 }191 @SuppressWarnings("unchecked")192 private <T> void cloneFields(ClassLoader targetCL, Class<T> targetClass, Object source, Object target,193 Map<Object, Object> referenceMap, boolean cloneStandardJavaTypes) {194 Class<?> currentTargetClass = targetClass;195 while (currentTargetClass != null) {196 for (Field field : currentTargetClass.getDeclaredFields()) {197 if (field.getAnnotation(doNotClone) != null) {198 continue;199 }200 field.setAccessible(true);201 try {202 final Field declaredField = Whitebox.getField(getType(source), field.getName());203 declaredField.setAccessible(true);204 final Object object = declaredField.get(source);205 final Object instantiatedValue;206 if (object == source) {207 instantiatedValue = target;208 } else if (referenceMap.containsKey(object)) {209 instantiatedValue = referenceMap.get(object);210 } else {211 if (object == null && !isIterable(object)) {212 instantiatedValue = object;213 } else {214 Class<Object> type = getType(object);215 if (type.getName().equals("void")) {216 type = Class.class.cast(Class.class);217 }218 final Class<Object> typeLoadedByCL = ClassLoaderUtil.loadClass(type, targetCL219 );220 if (type.isEnum()) {221 instantiatedValue = getEnumValue(object, typeLoadedByCL);222 } else {223 instantiatedValue = performClone(typeLoadedByCL, object, cloneStandardJavaTypes);224 }225 }226 }227 final boolean needsUnsafeWrite = field.isEnumConstant() || isStaticFinalModifier(field);228 if (needsUnsafeWrite) {229 UnsafeFieldWriter.write(field, target, instantiatedValue);230 } else {231 field.set(target, instantiatedValue);232 }233 } catch (RuntimeException e) {234 throw e;235 } catch (Exception e) {236 throw new RuntimeException(e);237 }238 }239 currentTargetClass = currentTargetClass.getSuperclass();240 }241 }242 private static <T> boolean isStandardJavaType(Class<T> targetClass) {243 return targetClass.getName().startsWith("java.");244 }245 private static boolean isStaticFinalModifier(final Field field) {246 final int modifiers = field.getModifiers();247 return Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)248 || field.getDeclaringClass().equals(Character.class) && field.getName().equals("MIN_RADIX");249 }250 private static boolean isIterable(final Object object) {251 return object != null && isIterable(object.getClass());252 }253 private static boolean isIterable(final Class<?> cls) {254 return Iterable.class.isAssignableFrom(cls);255 }256 @SuppressWarnings({ "unchecked", "rawtypes" })257 private static Enum getEnumValue(final Object enumValueOfSourceClassloader,258 final Class<Object> enumTypeLoadedByTargetCL) {259 return Enum.valueOf((Class) enumTypeLoadedByTargetCL, ((Enum) enumValueOfSourceClassloader).toString());260 }261 private Object instantiateArray(ClassLoader targetCL, Class<?> arrayClass, Object objectToClone,262 boolean cloneStandardJavaTypes) {263 final int arrayLength = Array.getLength(objectToClone);264 final Object array = Array.newInstance(arrayClass.getComponentType(), arrayLength);265 for (int i = 0; i < arrayLength; i++) {266 final Object object = Array.get(objectToClone, i);267 final Object performClone;268 if (object == null) {269 performClone = null;270 } else {271 performClone = performClone(ClassLoaderUtil.loadClass(getType(object), targetCL),272 object, cloneStandardJavaTypes);273 }274 Array.set(array, i, performClone);275 }276 return array;277 }278 /**279 * Most of this code has been copied from the Sun14ReflectionProvider in the280 * XStream project. Some changes has been made, namely if the field is281 * static final then the {@link Unsafe#staticFieldOffset(Field)} method is282 * used instead of {@link Unsafe#objectFieldOffset(Field)}.283 * 284 * @author Joe Walnes285 * @author Brian Slesinsky286 * @author Johan Haleby287 */288 private static class UnsafeFieldWriter {...
performClone
Using AI Code Generation
1 at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)2 at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)3 at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)4 at java.lang.reflect.Field.set(Field.java:764)5 at org.powermock.classloading.DeepCloner$1.visit(DeepCloner.java:94)6 at org.powermock.classloading.DeepCloner$1.visit(DeepCloner.java:91)7 at java.lang.reflect.Field.accept(Field.java:710)8 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:91)9 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:53)10 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:34)11 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:24)12 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:19)13 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:14)14 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:9)15 at org.powermock.classloading.DeepCloner.clone(DeepCloner.java:4)16 at org.powermock.classloading.DeepClonerTest.testClone(DeepClonerTest.java:34)17Connection connection = PowerMockito.mock(Connection.class);18PoolableConnection poolableConnection = new PoolableConnection(connection, null, true, true, 1, 1);19PoolableConnection clone = (PoolableConnection) DeepCloner.clone(poolableConnection);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!