Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 790
user32262 Avatar asked Jul 10 '10 02:07

user32262


1 Answers

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
like image 192
BalusC Avatar answered Oct 02 '22 19:10

BalusC