How to print values of an object in Java when you do not have the source code for the class? [duplicate]
public class MyClass {
ClassABC abc = new ClassABC();
}
I just have a .class file of ClassABC. I want to print all the public, private, protected and default field values of "abc" object. How can I do this using Reflection?
You can get all fields by Class#getDeclaredFields()
. Each returns a Field
object of which you in turn can use the get()
method to obtain the value. To get the values for non-public fields, you only need to set Field#setAccessible()
to true
.
So, in a nut:
ClassABC abc = new ClassABC();
for (Field field : abc.getClass().getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value = field.get(abc);
System.out.printf("Field name: %s, Field value: %s%n", name, value);
}
See also:
- Reflection tutorial
You can also install the jython - a Python itnerpreter on the JVM, and use the builtin Python "dir" function.
It is great because it allows you to interact live with your objects:
[gwidion@powerpuff]$ jython
Jython 2.2.1 on java1.6.0_13
Type "copyright", "credits" or "license" for more information.
>>> import java.awt
>>> dir(java.awt.Window)
['active', 'addPropertyChangeListener', 'addWindowFocusListener', 'addWindowListener',
'addWindowStateListener', 'alwaysOnTop', 'alwaysOnTopSupported', 'applyResourceBundle',
'bufferStrategy', 'createBufferStrategy',...
精彩评论