2

I'm looking for a way to print all instantiated Objects in Java. There's an easy way with PHP using get_declared_classes():

<?php
print_r(get_declared_classes());
?>

Is there an equivalent in Java, that works just as easy as in PHP?

JohnnyFromBF
  • 9,873
  • 10
  • 45
  • 59
  • http://www.tutorialspoint.com/java/lang/class_getdeclaringclass.htm That should help you out, – Jordy Nov 20 '14 at 09:57
  • 1
    @user3122479 he needs complete list – Bogdan Burym Nov 20 '14 at 09:57
  • another way is Keep track of them while you instantiate them – Shailendra Sharma Nov 20 '14 at 10:00
  • 1
    This is an interesting requirement. I don't think there's a great way to do this in Java. I honestly don't even think the PHP version will work very well looking at its implementation - it's going to miss things. If you only care about certain objects I'd do what Shailendra Sharma suggested and just keep track of them as you make them. Otherwise I wouldn't trust any code to do this reliably without substantial effort. – sage88 Nov 20 '14 at 10:12

2 Answers2

1

Loading classes in Java is done via class loaders, so you can only ever hope to get all classes loaded by a given class loader. Note that one class can possibly be loaded by different class loaders and that it can even be loaded in different versions by different class loaders.

If you want to find out which classes have been loaded by a single class loader, check out How can I list all classes loaded in a specific class loader

A simple solution might be

Field f = ClassLoader.class.getDeclaredField("classes");
f.setAccessible(true);

Vector<Class> classes =  (Vector<Class>) f.get(classLoader);

But this depends on Suns implementation and might fail with other vendors.

Community
  • 1
  • 1
Polygnome
  • 7,639
  • 2
  • 37
  • 57
1

Well I did a little research myself and found out that for debugging purposes the easiest way is to start the JVM with the command line option -verbose:class like this:

java -verbose:class Example

It's going to list all instantiated classes and that does the job for me. Thanks for your help anyway.

JohnnyFromBF
  • 9,873
  • 10
  • 45
  • 59