I have written code to cast the object to the required type. And if the required type is a custom class object and it has another object we need to cast it recursively. BTW: I will know that I need to construct an object if the input is a hashMap. If in side a HashMap if another hashMap is there then I need to understand that its object inside an object. And inside object I need to build from the inner hashMap. To build it I will call the method recursively. Code I have depicted here. But these 2 classes Castor and MyBuilder both have become in cycles. I am not getting how to break it. If the method is not cyclic we can break dependecy. But with cycles can any one help? Any pattern can I introduce or how can I refactor this?
Thanks in advance.
Code is something like this : For faster access to cycle pl refer to : returnValue castPrimitive( .... and void setParameterToEntity.....
MyBuilder myBuilder = new MyBuilder();
class Castor {
public Object castToRequiredType( Type type, Object object) {
String typeString = type.toString();
Object returnValue = null;
if (myUtils.isTypePrimitive(typeString)) {
returnValue = castPrimitive(object.toString(), typeString);
}else if {
// some conditions and some casting logic.
}
else {
returnValue = myBuilder.buildCustomObject(this,typeString, object);
}
return returnValue;
}
// other methods which call castToRequiredType() recursively.
}
class MyBuilder{
buildCustomObject(Castor castor,
String classOfType, Object object){
Class<?> loadedClass = myUtils.loadClass(classOfType);
instance = loadedClass.newInstance();
HashMap<?, ?> myMap;
List<Method> declaredMethods = myUtils.getMethodsForClass(loadedClass);
for (Method method : declaredMethods) {
if (object instanceof HashMap<?, ?>) {
myMap = (HashMap<?, ?>) object;
// ITERATE THROUGH MAP AND CALL THE SET PARAMETER TO ENTITY METHOD.
}
}
}
return instance;
}
void setParameterToEntity(Castor caster,
Object instance, Method method, Object value) {
ype[] parameterTypes = method.getGenericParameterTypes();
Object castedValue = caster.castToRequiredType(
parameterTypes[0], value);
}
} }