我正在尝试在 Java Applet 中制作模态框架,如下所示:http://www.java2s.com/Tutorial/Java/0240__Swing/Showthegivenframeasmodaltothespecifiedowner.htm 。这段代码有 start() 函数,看起来像
public void start() throws Exception {
Class<?> clazz = Class.forName("java.awt.Conditional");
Object conditional = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
this);
Method pumpMethod = Class.forName("java.awt.EventDispatchThread").getDeclaredMethod(
"pumpEvents", new Class[] { clazz });
pumpMethod.setAccessible(true);
pumpMethod.invoke(Thread.currentThread(), new Object[] { conditional });
}.
当我打电话时
pumpMethod.invoke(Thread.currentThread(), new Object[] { conditional });
我有以下异常:
java.lang.RuntimeException: java.lang.IllegalArgumentException: object is not an instance of declaring class
at wizard.ModalFrameUtil.showAsModal(ModalFrameUtil.java:136)
at wizard.WizardCore.showWizardFrame(WizardCore.java:206)
at SelfRegistrationApplet$1.run(SelfRegistrationApplet.java:55)
at SelfRegistrationApplet$1.run(SelfRegistrationApplet.java:35)
at java.security.AccessController.doPrivileged(Native Method)
at SelfRegistrationApplet.RunSelfRegistrationApplet(SelfRegistrationApplet.java:32)
at SelfRegistrationApplet.init(SelfRegistrationApplet.java:26)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
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 wizard.ModalFrameUtil$EventPump.start(ModalFrameUtil.java:80)
at wizard.ModalFrameUtil.showAsModal(ModalFrameUtil.java:133)
... 8 more
您能否告诉我此调用中有什么问题以及如何避免此异常?
最佳答案
它的意思是 Thread.currentThread()
返回的 Thread
对象不是 EventDispatchThread
的实例。
避免这个问题的方法是找出该对象的真正类是什么,并使用那个类来获取Method
对象。 (您应该能够通过在尝试调用该方法的位置打印从 Thread.currentThread().getClass() 获取的对象来找出它是什么。
invoke
的 Javadoc 是这样说的:
"Throws
IllegalArgumentException
- if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion."
我对您的代码的解读是,您拥有正确数量和类型的实际参数,因此这一定是线程类的问题。
关于使用反射调用 PumpEvents 时出现 java.lang.illegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035188/