Search code examples
reflectionjvmasmxaopjavassist

Invoking methods from Javassist, that have objects as parameter


I have following class structure -

class Student{
    int age;
    String name;
}

class Group{
   Student allStudents[];
   int avgAge;
}

class Handler{

    public int myFunction(Group g){
        ...
        do something with 'g'
        ...
        return k;
    }
}

I want to invoke the function, 'myFunction' from Javassist using a custom 'Group' object and test the behaviour of the function for this object.

In a different scenario, I'm able to work with functions with parameters of primitive data type as follows-

ctBehavior.insertBefore("{for (int i=0; i < $args.length; i++) {System.out.println($args[i]);}}");

I want to do something like this for parameters that are custom objects.


Solution

  • Javassist lets you code out anything that you could write in Java (v1.4). Additionally, it gives you a few makro commands. If you want to create a group object, depending on its constructor, it would look something like:

    "myFunction(new Group((Student[]) $args[0], Integer.valueOf((Integer) $args[1])));"
    

    Note that Javassist does not automatically box or unbox your values. Any value read by $args is boxed and of type Object. This is most likely the problem you are observing.