有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将JDK代理的代理实例传递到调用处理程序?

我查过了this 堆垛溢流柱。但我还是不明白

在JDK代理中,代理。newInstance(arg1、arg2、arg3)创建新的代理实例。当我们在此代理实例上调用一个方法时,它将调用其关联的调用处理程序。调用处理程序的invoke方法将调用委托给实际方法

invoke方法有3个参数。第一个被称为进行调用的代理实例。我的疑问是代理实例是如何传递给调用处理程序invoke方法的

为了更清楚地理解我的疑问,请参阅下面的代码

接口

package proxyclasses;

public interface Animal {
    public abstract void eat(String food);
}

混凝土类

包代理类

public class Cow implements Animal {

    public void eat(String food) {
        System.out.println("Cow eats "+food);
    }

}

代理类

package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {

    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("Proxy "+proxy.getClass().getName());
        Object result = method.invoke(target, args);
        return result;
    }

}

主类

import java.lang.reflect.Proxy;

import proxy.MyInvocationHandler;
import proxyclasses.Animal;
import proxyclasses.Cow;


public class ProxyExample {
    public static void main(String args[]){
        Cow cow = new Cow();
        Animal proxInstance = (Animal)Proxy.newProxyInstance(Cow.class.getClassLoader(),Cow.class.getInterfaces(),new MyInvocationHandler(cow));
        proxInstance.eat("Grass");
    }
}

这里我的疑问是主类中的“proxInstance”是如何传递给myInvocationHandlers调用方法的


共 (1) 个答案

  1. # 1 楼答案

    Here my doubt is how the 'proxInstance ' in main class is passed to myInvocationHandlers invoke method?

    你似乎已经回答了你自己的问题

    when we call a method on this proxy instance it calls its associated invocation handler

    所以你有点像

    Method method = ...
    Object[] args = ...
    handler.invoke(this, method, args);
    

    其中this是封装处理程序的代理对象,即您调用的代理