How to use spoon to get the properties of a class in java?

155 Views Asked by At

I have a java file and I want to get the exception message for the exception type after the throw keyword

 // this is the code of D:\\ProjectFile\\AST\\Test\\000001\\test.java
 if (len < 0 || offset < 0 || len + offset > b.length) {
            String str = "index out of bounds";
            throw new IndexOutOfBoundsException(s);
        }

For example, I want to get the string, "index out of bounds" inthe "D:\ProjectFile\AST\Test\000001\test.java", because he is a property of IndexOutOfBoundsException

So, When I use spoon, I don't find enough examples to teach me


public static void main(String[] args) {
    Launcher launcher = new Launcher();

    launcher.addInputResource("D:\\ProjectFile\\AST\\Test\\000001\\test.java");

    launcher.buildModel();
    CtModel model = launcher.getModel();


    List<CtThrow> throwList = model.getElements(new TypeFilter<>(CtThrow.class));

    for (int i = 0; i < throwList.size();i++) {
        System.out.println(throwList.get(i).getThrownExpression());
    }
}

Using the code above, I can only get the following:

new java.lang.IndexOutOfBoundsException(s)

I can not get the value of s.

I want to be able to check the constructor of this exception type and get its property value, how should I do this?

2

There are 2 best solutions below

2
On

try it :

 IndexOutOfBoundsException e  = new java.lang.IndexOutOfBoundsException(s);
        Field[] field = e.getClass().getDeclaredFields();
        for(int i = 0 ; i<field.length ; i++)
            java.lang.System.out.print(field[i].get(e));

But it won't be able to get the value declared as private

0
On

You need some kind of data-flow analysis for this.

In Spoon, this is not in spoon-core but in submodule https://github.com/INRIA/spoon/tree/master/spoon-dataflow