Dynamic Proxy Method Interception

Wrap an interface implementation with Proxy.newProxyInstance so every method call is recorded first, the same trick frameworks use for auditing.

JavaData Integrity

Code

javasnippet
36 lines
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

interface Meter {
    int read(String meterId);
}

public class MeterAudit {

    public static void main(String[] args) {
        // 真实实现:代理最终委托给它
        Meter target = id -> id.length() * 10;

        Map<String, Integer> calls = new HashMap<>();
        InvocationHandler audit = (Object proxy, Method method, Object[] argv) -> {
            // 只拦截业务方法,Object 自带方法原样透传
            if (method.getDeclaringClass() != Meter.class) {
                return method.invoke(target, argv);
            }
            calls.merge(method.getName(), 1, Integer::sum);
            return method.invoke(target, argv);
        };

        Meter audited = (Meter) Proxy.newProxyInstance(
                Meter.class.getClassLoader(),
                new Class<?>[] {Meter.class},
                audit);

        System.out.println("read: " + audited.read("gas-01"));
        System.out.println("read again: " + audited.read("gas-01"));
        System.out.println("calls: " + calls);
    }
}

What the code does

The working surface is the classes Meter and MeterAudit and the function main — everything else is wiring.

Applying it

Running the file prints labeled results such as read:, read again:, calls: — each operation’s effect is visible in the output.

Statements that matter

return method.invoke(target, argv);

Interactive Tools for This Topic

FAQ

What does Dynamic Proxy Method Interception print when run?
Run it as a complete program — the output lines carry labels such as `read:`, `read again:`, `calls:`.