Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to figure out which inner anonymous class indicated by a class name?

Tags:

java

android

I used MAT tool in Eclipse to investigate a memory leak issue. I found that the leak was caused by an anonymous inner class instance in my app. 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 the which inner class com.mycompany.myproduct.MyActivity$3 indicates?

Thanks.

like image 361
Kai Avatar asked Oct 18 '11 00:10

Kai


3 Answers

On the Oracle compiler, they're numbered in order of occurrence in the class. I'm not sure if that's part of any specification or consistent with other implementations.

You could decompile the class--JD-GUI is a great tool for that--and then you'll see what you want to know. You could even just go with basic disassembly using javap -c. It'll give you a rough idea of where the classes occur.

like image 143
Ryan Stewart Avatar answered Nov 20 '22 01:11

Ryan Stewart


Hint: debugger somehow knows which classes are where. So you can, too!

Try using javap on 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 got name Test$1, the second one—Test$2. Hope tat helps.

For more specific information, decompile the specific classes you're interested in, e.g. javap -c -l Test\$2. Pay attention to line numbers: they will give you a hint on where in the source file the class was defined.

like image 44
alf Avatar answered Nov 20 '22 01:11

alf


When you compile your code securely you have MyActivity$1.class, MyActivity$2.class, MyActivity$3.class, and so on. You can use a java decompiler (over your .class) in order to identify the anonymus class that is throwing the exception.

like image 1
Ernesto Campohermoso Avatar answered Nov 19 '22 23:11

Ernesto Campohermoso