I am creating a library where i need to identify changes between two objects of same type and store the old and new value in an object. Type could be primitive,Collections and object. Logic is that if the two objects passed of same type and if its primitive then directly it can go for (==,!=) operators to check for equality. But if its collections of same type then it needs to iterate its elements and check for equality. And if its an Object then it has to go through its all fields and identify its type and accordingly it should compare.
Snippet of the code :-
def trackChanges(newRecord: Any, oldRecord: Any): Unit = {
if (newRecord.getClass() == oldRecord.getClass()) {
newRecord match {
// Primitive Data Types......
case u: Unit => primitiveHandling(newRecord, oldRecord)
case z: Boolean => primitiveHandling(newRecord, oldRecord)
case b: Byte => primitiveHandling(newRecord, oldRecord)
case c: Char => primitiveHandling(newRecord, oldRecord)
case s: Short => primitiveHandling(newRecord, oldRecord)
case i: Int => primitiveHandling(newRecord, oldRecord)
case j: Long => primitiveHandling(newRecord, oldRecord)
case f: Float => primitiveHandling(newRecord, oldRecord)
case d: Double => primitiveHandling(newRecord, oldRecord)
// Collections...
case list: List[_] => collectionHandling(newRecord, oldRecord)
case seq: Seq[_] => collectionHandling(newRecord, oldRecord)
// Object....
case l: AnyRef => objectHandling(newRecord, oldRecord)
}
}
// Checks primitive data for changes
def primitiveHandling(newRecord: Any, oldRecord: Any) {
println("Primitive Handling")
if (newRecord != oldRecord) {
var auditlog = new AuditLog(oldRecord.toString(), newRecord.toString())
}
}
// Check collection data for changes
def collectionHandling(newRecord: Any, oldRecord: Any) {
}
// Check Object data for changes
def objectHandling(newRecord: Any, oldRecord: Any) {
val newfields: Array[Field] = newRecord.getClass().getDeclaredFields
val oldfields: Array[Field] = oldRecord.getClass().getDeclaredFields
for (i <- 0 until newfields.length) {
if (newfields(i).getType.isPrimitive) {
newfields(i).setAccessible(true)
oldfields(i).setAccessible(true)
primitiveHandling(newfields(i).get(newRecord), oldfields(i).get(oldRecord))
} else {
val t_new: Class[_] = newfields(i).getType
val t_old: Class[_] = oldfields(i).getType
if (t_new == classOf[Seq[_]] && t_old == classOf[Seq[_]]) {
collectionHandling(newfields(i).get(newRecord), oldfields(i).get(oldRecord))
for {
newelement <- t_new.getName
oldelement <- t_old.getName
} trackChanges(newelement, oldelement)
println("Sequence")
}
if (t_new == classOf[List[_]] && t_old == classOf[List[_]]) {
for {
newelement <- t_new.getName
oldelement <- t_old.getName
} trackChanges(newelement, oldelement)
println("List")
}
}
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire