I've recently changed my schema a bit so my classes inherit from a super class, problem is my comparison method which generates an audit log, using Java reflect, is now only looping through the fields of the child class, not the superclass, is there a way to get all the FIELDS? or do I need to cast it into the super class.....?
Heres my method below:
public static <T> String GenerateChangeLogForEntity(T old, T updated) { String text = ""; try { Field[] fields = old.getClass().getDeclaredFields(); if(fields != null) { BaseController.getLogger().info("Z1 num fields:"+fields.length); for (Field field : fields) { if(field.isAnnotationPresent(Column.class)) { String fieldName = field.getName(); BaseController.getLogger().info(field.getName()); if(field.isAnnotationPresent(Variation.class)) { Variation v = field.getAnnotation(Variation.class); fieldName = v.friendlyName(); } field.setAccessible(true); if(field.get(old) != null && field.get(updated) != null) { if(!(field.get(old)).equals(field.get(updated))) { text += "<p><span class=\"field-name\">"+fieldName+"</span> changed from: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(old))+"</strong> to: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(updated)) + "</strong></p>"; } } if(field.get(old) == null && field.get(updated) != null) { text += "<p><span class=\"field-name\">"+fieldName+"</span> changed from: <strong>empty</strong> to: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(updated)) + "</strong></p>"; } if(field.get(old) != null && field.get(updated) == null) { text += "<p><span class=\"field-name\">"+fieldName+"</span> changed from: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(updated))+"</strong> to <strong>empty</strong>" + "</p>"; } field.setAccessible(false); } } } } catch(IllegalAccessException e) {} return text; }
Reflection API also provides method to get specific public field of a class through getField() method. This method look for the field in the specified class reference and then in the super interfaces and then in the super classes. Field field = Class.
Now how can i get fields of parent class in this case 'a'. You can use getField() with public fields. Otherwise, you need to loop through parent classes yourself.
It's very bad because it ties your UI to your method names, which should be completely unrelated. Making an seemingly innocent change later on can have unexpected disastrous consequences. Using reflection is not a bad practice.
You can use this.getClass().getSuperClass()
until this getSuperClass()
method returns null to get the parent fields.
So, the best would be that you factorize your code. Implement one method that takes a list of Field
as parameter and do your logical part within it, and a main method that search for fields through a while(superClass != null)
loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With