Is there any way to access the compiler's number for an anonymous class in Java using reflection?
Say I have a Class object which represents an anonymous inn开发者_开发知识库er 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?
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.
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.
Simply do a getClass() from your anonymous class.
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.
精彩评论