How to determine which internal anonymous class is indicated by the name of the class?

I used the MAT tool in Eclipse to study the memory leak problem. I found that the leak was caused by an anonymous instance of the inner class in my application. The class name displayed in MAT is com.mycompany.myproduct.MyActivity $ 3. There are many anonymous inner classes defined in MyActivity.java. How do I know which inner class com.mycompany.myproduct.MyActivity $ 3 points to?

Thanks.

+7
source share
4 answers

In the Oracle compiler, they are numbered in the order they appear in the class. I am not sure if this part of any specification is consistent with other implementations.

You can decompile the class - the JD-GUI is a great tool for this - and then you will see what you want to know. You can even just do basic disassembly with javap -c . This will give you an idea of ​​where the classes originate.

+4
source

Hint: the debugger somehow knows what classes are. So you can too!

Try using javap in this example with two anonymous classes:

 import java.util.*; public class Test { public static void main(String [] args) { Map m = new HashMap(){{System.out.print(1);}}; Map m1 = new HashMap(){{System.out.print(2);}}; } } 

Compile it and run javap -c -l :

 $ javap -c -l Test Compiled from "Test.java" public class Test extends java.lang.Object{ public Test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return LineNumberTable: line 3: 0 public static void main(java.lang.String[]); Code: 0: new #2; //class Test$1 3: dup 4: invokespecial #3; //Method Test$1."<init>":()V 7: astore_1 8: new #4; //class Test$2 11: dup 12: invokespecial #5; //Method Test$2."<init>":()V 15: astore_2 16: return LineNumberTable: line 5: 0 line 7: 8 line 9: 16 } 

As you can see, the first class received the name Test$1 , the second - Test$2 . Hope that helps.

For more information, decompile the classes you are interested in, for example. javap -c -l Test\$2 . Pay attention to line numbers: they will give you a hint about where the class was defined in the source file.

+4
source

When you compile your code reliably, you have the class MyActivity $ 1.class, MyActivity $ 2.class, MyActivity $ 3.class, etc. You can use the java decompiler (above your .class) to identify the anonymous class that throws an exception.

+1
source

The whole point of anonymous classes is that they are exactly that. Because you find it hard to figure out which one it comes from. Numbering usually starts with one, so I guess this will be the third declared anonymous class, which is your problem.

In this situation, you might be better off reorganizing your code so that there are no anonymous classes. Otherwise, I suggest installing a debugger and typing code.

0
source

All Articles