Best Powermock code snippet using org.powermock.classloading.DeepCloner.instantiateArray
Source:DeepCloner.java
...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 }...
instantiateArray
Using AI Code Generation
1import org.powermock.classloading.DeepCloner2import groovy.transform.CompileStatic3import java.util.Arrays4import java.util.stream.Collectors5def instantiateArray(Class clazz, int length) {6 def array = Array.newInstance(clazz, length)7 return DeepCloner.clone(array)8}9def b = instantiateArray(Integer, 3)10assert a.getClass() == b.getClass()11assert a.size() == b.size()12assert Arrays.equals(a, b)13def d = instantiateArray(String, 3)14assert c.getClass() == d.getClass()15assert c.size() == d.size()16assert Arrays.equals(c, d)17def f = instantiateArray(Object, 6)18assert e.getClass() == f.getClass()19assert e.size() == f.size()20assert Arrays.equals(e, f)21def h = instantiateArray(Map.Entry, 3)22assert g.getClass() == h.getClass()23assert g.size() == h.size()24assert Arrays.equals(g, h)25def j = instantiateArray(Map.Entry, 3)26assert i.getClass() == j.getClass()27assert i.size() == j.size()28assert Arrays.equals(i, j)29def l = instantiateArray(int, 3)30assert k.getClass() != l.getClass()31assert k.size() == l.size()32assert Arrays.equals(k, l)33def n = instantiateArray(String, 3)34assert m.getClass() == n.getClass()35assert m.size() == n.size()36assert Arrays.equals(m, n)
instantiateArray
Using AI Code Generation
1import org.powermock.classloading.DeepCloner;2public class TestClass {3 public void testMethod() {4 String[] array = new String[]{"a", "b", "c"};5 String[] clonedArray = (String[]) DeepCloner.instantiateArray(array);6 methodThatTakesArrayAsParameter(clonedArray);7 }8 public void methodThatTakesArrayAsParameter(String[] array) {9 }10}11 at TestClass.testMethod(TestClass.java:7)12 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)13 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)14 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)15 at java.lang.reflect.Method.invoke(Method.java:498)16 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)17 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)18 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)19 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)20 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)21 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)22 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)23 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)24 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)25 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)26 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)27 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)28 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
instantiateArray
Using AI Code Generation
1import org.powermock.api.support.membermodification.MemberModifier;2import org.powermock.classloading.DeepCloner;3import org.powermock.core.classloader.annotations.PrepareForTest;4import org.powermock.modules.junit4.PowerMockRunner;5import org.powermock.reflect.Whitebox;6import org.junit.Test;7import org.junit.runner.RunWith;8import static org.junit.Assert.assertArrayEquals;9import static org.junit.Assert.assertEquals;10import static org.junit.Assert.assertTrue;11import static org.junit.Assert.assertFalse;12import static org.junit.Assert.assertNotNull;13@RunWith(PowerMockRunner.class)14@PrepareForTest(DeepCloner.class)15public class DeepClonerTest {16 public void testInstantiateArray() throws Exception {17 Object[] array = new Object[3];18 array[0] = "one";19 array[1] = 2;20 array[2] = 3.0;21 Object[] clonedArray = (Object[]) Whitebox.invokeMethod(DeepCloner.class, "instantiateArray", array);22 assertNotNull(clonedArray);23 assertFalse(clonedArray == array);24 assertArrayEquals(array, clonedArray);25 }26}
instantiateArray
Using AI Code Generation
1public class PrimitiveObsession {2 private int[] array = { 1, 2, 3, 4, 5 };3 public int[] getArray() {4 return array;5 }6 public void setArray(int[] array) {7 this.array = array;8 }9}10public class PrimitiveObsessionTest {11 public void testPrimitiveObsession() throws Exception {12 PrimitiveObsession primitiveObsession = new PrimitiveObsession();13 int[] array = primitiveObsession.getArray();14 int[] arrayCopy = (int[]) DeepCloner.instantiateArray(array);15 array[0] = 100;16 assertEquals(1, arrayCopy[0]);17 }18}19 at org.junit.Assert.assertEquals(Assert.java:115)20 at org.junit.Assert.assertEquals(Assert.java:144)21 at com.jbrains.test.PrimitiveObsessionTest.testPrimitiveObsession(PrimitiveObsessionTest.java:19)
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!!