public static void main(String[] args) throws Exception { Class clazz = Class.forName("java.net.SocksSocketImpl");
Constructor c = clazz.getDeclaredConstructor();
c.setAccessible(true);
SocketImpl socketImpl = (SocketImpl) c.newInstance(null);

Class clazz2 = Class.forName("java.net.PlainSocketImpl");

Method bind = clazz2.getDeclaredMethod("bind", new Class[] {
InetAddress.class, int.class });
bind.setAccessible(true);

InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
bind.invoke(socketImpl, new Object[] { inetAddress, 0 }); System.out.println(socketImpl);
}
SocksSocketImpl类继承至PlainSocketImpl类,现在我想要调用bind方法,bind方法访问权限是properted。
上面的代码出现如下异常。Exception in thread "main" java.lang.reflect.InvocationTargetException
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 Test.main(Test.java:44)
求高手,这里我要调用一下bind方法。谢谢。

解决方案 »

  1.   

    getDeclaredMethodgetMethod
      

  2.   

    这个错误应该不是反射导致的,你可以看下API,是由于调用的方法产生异常导致的这个错误
    你自己写个小例子 让调用方法抛异常试试
    或者
      try{
            bind.invoke(socketImpl, new Object[] { inetAddress, 0 });
            }
            catch(InvocationTargetException e)
            {
             System.out.println(e.getTargetException());
            }