raphw / byte-buddy

Runtime code generation for the Java virtual machine.
https://bytebuddy.net
Apache License 2.0
6.28k stars 807 forks source link

[Question] How to find all the member variables used in the method? #1704

Closed lucas-myx closed 1 month ago

lucas-myx commented 2 months ago

@raphw Sorry to inflict myself on you again like this! I need find all the member variables on foo() method, and then replace these field on bar() method. I can use MemberSubstitution replace field access on bar() method, but I'm not quite sure how to find the member variables its using from a foo() method firstly, because I don't know how many variables are used in this method, I need to find out all of them. as follow demo:

public class A {
    public String foo;
    public String bar;
    public void foo() {
        foo = "a";
        bar = "b";
        int c = 1;
    }
    public void bar() {
       System.out.println(foo);
    }
}

So I want to ask can Bytebuddy find out member variables used in foo() method? Thank you very much for any suggestions!

raphw commented 2 months ago

You can use a matcher that finds all field accessed in a method. That should be straight forward? You can match the field's declaring type, for example. Internal variables are never picked up.

lucas-myx commented 2 months ago

Thank you for your response! I will try it out.