1

I have a class like below

class A{
    private var1, var2;

    public void methodA(){
        sout(var1);
    }
    public void methodB(){
        sout(var1);
        sout(var2);
    }
}

Here in that code snippet I have class with two instance variables var1, var2 and two methods methodA, methodB. var1 is referenced in both methodA and methodB. How can I extract this information from a java class?

  • Parse the source code and analyze the resulting model. – lexicore Feb 14 '18 at 15:56
  • 1
    Are you asking how to parse java source code? Are you asking how to analyse a compiled class file? In any case: – GhostCat Feb 14 '18 at 16:00
  • 1
    Unfortunately your question boils down to "somebody please please help me with this". But we do not regard such requests as *questions* in the scope of this site. Please read [this](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) carefully to understand why that is. Then consider to either delete this question and putting up a new, more precise question within the scope of this community. Alternatively, you could [edit], rework and improve this question. Thanks! – GhostCat Feb 14 '18 at 16:00
  • I am new at javaparsing. Can you please give some detail procedure @lexicore ? Thanks – Pritom Saha Akash Feb 14 '18 at 16:02
  • This is way too broad. I suggest you read up on Reflection in Java, and return if you have a specific problem implementing what you've learnt. – Toby Speight Feb 14 '18 at 16:03
  • @TobySpeight You can't solve this with reflection, can you? – lexicore Feb 14 '18 at 16:03
  • @lexicore, I missed the bit about reading the method body to see which variables were referenced (all that bold makes it hard to read). Maybe reflection isn't quite enough on its own, then (it's a decade or two since I did Java). The question is still too general for SO. – Toby Speight Feb 14 '18 at 16:05
  • @PritomSahaAkash Check [JavaParser](http://javaparser.org/), it is quite easy to use. [No](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question), I will not give you the detail procedure. – lexicore Feb 14 '18 at 16:05
  • @TobySpeight This is not doable with reflection. Just saying so that noone is misguided. – lexicore Feb 14 '18 at 16:06
  • Thank you @lexicore and I will check JavaParser. – Pritom Saha Akash Feb 14 '18 at 16:09

1 Answers1

2

You can use this library: JavaParser Core

    JavaAnalyzer jpa = new JavaAnalyzer(this, "A.java");

    AtomicBoolean var1IsReferencedInMethodA = new AtomicBoolean(false);

    jpa.visit((MethodDeclaration methodDeclaration) -> {
        var1IsReferencedInMethodA.setTrueWhen(methodDeclaration.getName().equals("methodA")
                && (methodDeclaration.getBody().getStmts().get(0).toString().equals("var1")));
    });

    System.out.println("var1 is referenced in methodA(): " + var1IsReferencedInMethodA);
Pavlo Plynko
  • 586
  • 9
  • 27