import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class HelloProxy implements InvocationHandler { private Object target; public HelloProxy(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method " + method.getName()); Object result = method.invoke(target, args); System.out.println("After method " + method.getName()); return result; } public static void main(String[] args) { Hello hello = new HelloImpl(); Hello proxy = (Hello) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), new HelloProxy(hello)); proxy.sayHello("world"); } } class HelloImpl implements Hello { public void sayHello(String name) { System.out.println("Hello, " + name); } }
时间: 2024-04-02 09:34:54 浏览: 155
根据这段代码,运行proxy.sayHello("world")的输出将会是:
Before method sayHello
Hello, world
After method sayHello
这是因为这段代码使用了Java动态代理机制,在HelloProxy类的invoke方法中对代理对象的sayHello方法进行了特定的处理。在代理对象的sayHello方法被调用之前会输出"Before method sayHello",在代理对象的sayHello方法被调用之后会输出"After method sayHello"。同时,sayHello方法的实现"Hello, world"也会被输出,因为在invoke方法中调用了target对象(即HelloImpl实例)的sayHello方法。
相关问题
Post-processing of FactoryBean's singleton object failed; nested exception is java.lang.RuntimeException: java.lang.reflect.InaccessibleObjectException: Unable to make field protected java.lang.reflect.InvocationHandler java.lang.reflect.Proxy.h accessible: module java.base does not "opens java.lang.reflect" to unnamed module @752325ad
这个问题可能是由于 FactoryBean 的单例对象的后处理失败导致的,其中嵌套的异常是 java.lang.RuntimeException: java.lang.reflect.InaccessibleObjectException: Unable to make field protected java.lang.reflect.InvocationHandler java.lang.reflect.Proxy.h accessible: module java.base does not "opens java.lang.reflect" to unnamed module @752325ad。可能需要检查代码中是否有对该对象的反射操作,并确保模块中已经打开了 java.lang.reflect。
JDK动态代理是通过java.lang.reflect.Proxy 类来实现的
是的,您说得对。JDK动态代理是通过java.lang.reflect.Proxy类来实现的。在Java中,动态代理是一种机制,它允许在运行时创建代理对象,并将方法调用转发到实际的对象。通过使用Proxy类和InvocationHandler接口,可以在运行时生成代理类,并在代理类中实现代理逻辑。这种机制在许多领域中都有应用,例如AOP(面向切面编程)。
阅读全文
相关推荐

















