typeToMock = (Class<T>) new ClassReplicaCreator().createClassReplica(type); } else { typeToMock = type;
private static <T> Class<?> createReplicaType(Class<T> type, boolean isStatic, ConstructorArgs constructorArgs) { ClassReplicaCreator classReplicaCreator = new ClassReplicaCreator(); Class<?> replicaType = null; if (isStatic || constructorArgs == null) { replicaType = classReplicaCreator.createClassReplica(type); } else { try { replicaType = classReplicaCreator.createInstanceReplica(constructorArgs.getConstructor().newInstance(constructorArgs.getInitArgs())); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { Throwable targetException = ((InvocationTargetException) e).getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } return replicaType; }
final String originalClassName = clazz.getName(); CtClass originalClassAsCtClass; final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz)); try { originalClassAsCtClass = classpool.get(originalClassName); copyFields(originalClassAsCtClass, newClass); addDelegatorField(delegator, newClass); final String code = getReplicaMethodDelegationCode(delegator.getClass(), ctMethod, POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME); CtMethod make2 = CtNewMethod.copy(ctMethod, newClass, null); newClass.addMethod(make2);
builder.append(ctMethod.getName()); builder.append("\", "); final String parametersAsString = getParametersAsString(getParameterTypes(ctMethod)); if ("".equals(parametersAsString)) { builder.append("null");
public <T> Class<T> createClassReplica(Class<T> clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz cannot be null"); } ClassPool classpool = ClassPool.getDefault(); final String originalClassName = clazz.getName(); CtClass originalClassAsCtClass; final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz)); try { originalClassAsCtClass = classpool.get(originalClassName); CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods(); for (CtMethod ctMethod : declaredMethods) { final String code = getReplicaMethodDelegationCode(clazz, ctMethod, null); CtNewMethod.make(ctMethod.getReturnType(), ctMethod.getName(), ctMethod.getParameterTypes(), ctMethod.getExceptionTypes(), code, newClass); } return (Class<T>) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain()); } catch (Exception e) { throw new RuntimeException(e); } }
private <T> Class<T> getMockType(final Class<T> type) { final Class<T> typeToMock; if (isFinalJavaSystemClass(type)) { typeToMock = new ClassReplicaCreator().createClassReplica(type); } else { typeToMock = type; } return typeToMock; }