views:

52

answers:

2
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?

+8  A: 

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:

BalusC
Thats exactly what I was looking for. Thanks!
You're welcome.
BalusC
+2  A: 

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',...
jsbueno