开发者

How to print values of an object in Java when you do not have the source code for the class? [duplicate]

This question already has answers here: 开发者_运维百科 Printing all variables value from a class (9 answers) Closed 6 years ago.
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',...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜