本帖最后由 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>
复制代码 |