views:

57

answers:

4

Say I have a Class object which represents an anonymous inner class. Is there any way I can get the compiler's number for the class it created? For example I have a class here whose compilation has resulted in a

Thing$1.class

file being created. How can I find out this number from the Class object?

A: 

You can take the name of the class ("Thing$1"), find the last $ sign and parse the text after that...

String name = clazz.getName();
int number = Integer.parseInt(name.substring(name.lastIndexOf('$') + 1));

It's pretty hacky, but then I'd imagine you're in a pretty specialized situation, wanting to know this sort of thing.

Jon Skeet
+5  A: 

This works:

    Object o =new Object(){};
    String name = o.getClass().getName();
    int number = Integer.parseInt(name.substring(name.lastIndexOf('$')+1));

I can't imagine anything useful you could do with that number, though. More importantly, this naming scheme for anonymous classes is AFAIK not mandated by the language or VM specs. It's an implementation detail that could change.

Michael Borgwardt
1.5/JLS 3rd Ed tightened it up. Can't remember exactly what the constraints are atm, nor understand why anyone would want to know.
Tom Hawtin - tackline
A: 

Simply do a getClass() from your anonymous class.

Webinator
A: 

I understand you want to know the number (or the resourceURL) from the running class reference, don't you?

Maybe you can use Class.getName()...

Or you can get the containing class (Class.getDeclaringClass()) and look for your class inside its decalred classes: Class.getDeclaredClasses(). That gives you the position inside the declaring class and you can know which number will be assiged.

helios