3

I'm working on performance monitoring system, which could inject its routines into existing assembly. For that, I'm trying to understand how dalvik code works.

Here's an illustration of what I'm trying to accomplish. Input class could look like this:

class MyClass{
    public MyClass(__params__){
        //initialization code
    }
}

I want to add code for the class to look like this:

class MyClass{
    public MyClass(__params__){
        this(_params__,0);
        //tracking and performance initialization code
    }

    public MyClass(__params__, int init){
        //old initialization code
    }
}

What was causing most bugs so far is the distinction between invoke-direct and invoke-virtual when calling one constructor from another.

When calling methods, this is straightforward (if method is private, it's called with invoke-direct, otherwise invoke-virtual). This doesn't seem to be the case for constructors.

What are the rules of calling invoke-direct vsinvoke-virtual when invoking one constructor from another?

Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224

1 Answers1

3

You can invoke one constructor from another:

public class Foo
{
    private int x;

    public Foo()
    {
        this(1);
    }

    public Foo(int x)
    {
        this.x = x;
    }
}

Note:

  1. you can only chain to one constructor, and it has to be the first statement in your constructor body.

  2. If you want to chain inherited constructor, you can use super instead of this.

  3. invoke-direct is used for constructors and private methods

seahawk
  • 1,872
  • 12
  • 18