黑马程序员技术交流社区
标题:
关于动态代理的案列?求解决?
[打印本页]
作者:
simonqian
时间:
2013-6-4 11:32
标题:
关于动态代理的案列?求解决?
本帖最后由 simonqian 于 2013-6-4 14:21 编辑
<P>package com.eight;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//接口
interface Hello
{
void sayHello(String to);
void print(String s);
}
//接口的实现类
class HelloImpl implements Hello
{
public void print(String s)
{
System.out.println("Print "+s);
}
public void sayHello(String to)
{
System.out.println("Say Hello to "+to);
}
}
//生成与代理类相关的InvocationHandler对象
class LogHandler implements InvocationHandler
{
private Object obj;
public LogHandler(Object ojb)
{
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
doBefore();
Object res = method.invoke(obj, args);
after();
return res;
}
private void doBefore()
{
System.out.println("before......!");
}
private void after()
{
System.out.println("after......!");
}
}
public class proxyDemo
{
public static void main(String[] args)
{
HelloImpl helloImpl = new HelloImpl();
LogHandler handler = new LogHandler(helloImpl);
Hello hello =
(Hello)Proxy.newProxyInstance(helloImpl.getClass().getClassLoader(),
helloImpl.getClass().getInterfaces(), handler);
hello.print("All the test");
hello.sayHello("Denny");
}
}
before......!
Exception in thread "main" java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.eight.LogHandler.invoke(proxyDemo.java:38)
at com.eight.$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$Proxy0.print(Unknown Source)
at com.eight.proxyDemo.main(proxyDemo.java:60)</P>
<P>为什么会出现上面的异常呀?
</P>
复制代码
作者:
simonqian
时间:
2013-6-4 14:21
public LogHandler(Object ojb)
{
this.obj = obj;//原来是这里写错了,哈哈
}
作者:
袁梦希
时间:
2013-6-4 14:48
哈哈哈 自问自答的精神很可取
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2