← Quiz: Spring AOP and Proxies: all 10 questions
Quiz: Spring AOP and Proxies · Question 7 of 10
What does this print? (code)
What does this print?
import java.lang.reflect.*;
interface Counter { int next(); int twice(); }
class RealCounter implements Counter {
int n = 0;
public int next() { return ++n; }
public int twice() { next(); return next(); }
}
public class Main {
static int calls = 0;
public static void main(String[] args) {
Counter real = new RealCounter();
Counter c = (Counter) Proxy.newProxyInstance(Counter.class.getClassLoader(),
new Class<?>[]{Counter.class}, (p, m, a) -> { calls++; return m.invoke(real, a); });
c.twice();
c.next();
System.out.println(calls + " " + c.next());
}
}
- A.4 4
- B.2 4
- C.3 4
- D.2 3
Answer & explanation
Correct answer: 2 4
Only twice() and the first next() go through the proxy (2 calls); the inner next() calls do not. n is 4 after the last call.
Can you get the rest right without peeking?
Take the timed Quiz: Spring AOP and Proxies quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →