当您没有类的源代码时,如何在 Java 中打印对象的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3217603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print values of an object in Java when you do not have the source code for the class?
提问by user32262
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?
我只有一个 ClassABC 的 .class 文件。我想打印“abc”对象的所有公共、私有、受保护和默认字段值。我如何使用反射来做到这一点?
采纳答案by BalusC
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
.
您可以通过 获取所有字段Class#getDeclaredFields()
。每个返回一个Field
对象,您可以使用该get()
方法获取该对象的值。要获取非公共字段的值,您只需设置Field#setAccessible()
为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:
也可以看看:
回答by jsbueno
You can also install the jython - a Python itnerpreter on the JVM, and use the builtin Python "dir" function.
您还可以在 JVM 上安装 jython——一个 Python itnerpreter,并使用内置的 Python“dir”函数。
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',...