Created
August 6, 2015 15:47
-
-
Save mrhether/422b0fbcbca1bf21febc to your computer and use it in GitHub Desktop.
Reflection Method to print the insides of an object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String printInsides(Object object) { | |
StringBuilder result = new StringBuilder(); | |
String newLine = "\n"; | |
result.append( object.getClass().getName() ); | |
result.append( " Object { " ); | |
result.append(newLine); | |
//determine fields declared in this class only (no fields of superclass) | |
Field[] fields = object.getClass().getDeclaredFields(); | |
//print field names paired with their values | |
for ( Field field : fields ) { | |
result.append(" "); | |
try { | |
field.setAccessible(true); | |
result.append(field.getName() ); | |
result.append(": "); | |
//requires access to private field: | |
result.append( field.get(object) ); | |
} catch ( IllegalAccessException ex ) { | |
Log.w(TAG, ex.getMessage()); | |
} | |
result.append(newLine); | |
} | |
result.append(" }"); | |
return result.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment