Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoke-virtual vs invoke-direct in constructors

Tags:

java

dalvik

smali

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?

like image 464
Arsen Zahray Avatar asked Aug 19 '26 03:08

Arsen Zahray


1 Answers

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

like image 168
seahawk Avatar answered Aug 21 '26 17:08

seahawk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!