timekeeper
timekeeper

Reputation: 718

Fetch updated argument for a method using AspectJ

A class where aspect join point happens

class A {
 ...
 @PointCutHere
 public void method(List<String> arg1) {
    arg1 = Arrays.asList("A", "B");
    ...
 }
}

CustomAspect.java

@Aspect
class CustomAspect {

    @Pointcut("@annotation(PointCutHere)")
    public void pointCut(){
    }

    @Around("pointCut()")
    public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
        joinPoint.proceed();
        Object[] args = joinPoint.getArgs();
        System.out.println(((List<String>)args[0]).toString());
    }
}

Say, another class calls A.method(new LinkedList());

Here, I am trying to print inside @Around the latest updated value of an argument passed into the method.

In this example,

the actual output I am getting is: []

expected output I want: ["A", "B"]

In my understanding, since it's Java, the arguments are pass by reference. Why isn't AspectJ not showing the expected updated value?

Upvotes: 0

Views: 66

Answers (2)

timekeeper
timekeeper

Reputation: 718

The miss was re-assigning the entire variable instead of using setters. When I replaced arg1 = Arrays.asList("A", "B"); to arg1.addAll(["A", "B"]);, it worked.

So, never re-assign the variable. Use the objects method (setter or any other method()) for this purpose.

Upvotes: 0

kriegaex
kriegaex

Reputation: 67297

A String is not a normal object. Quote from the Javadoc:

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

I.e. that String instances, while behaving like objects otherwise, behave more like primitives when it comes to assigning new values to them.

Upvotes: 1

Related Questions