public class RunnableSupport implements Runnable {
private MyClient myClient;
private String frameType;
Method[] methodList;
Constructor> constructor;
Class> myClass;
private JFrame mainFrame;
private boolean mustClose;
private int width;
private int height;
private int x;
private int y;
public RunnableSupport(MyClient myClient, String frameType, int width,
int height, int x, int y, boolean mustClose) {
this.myClient = myClient;
this.frameType = frameType;
this.height = height;
this.width = width;
this.x = x;
this.y = y;
this.mustClose = mustClose;
}
@Override
public void run() {
try {
myClass = Class.forName("it.polimi.social.frame." + frameType);
constructor = myClass
.getDeclaredConstructor(new Class[] { MyClient.class });
methodList = myClass.getDeclaredMethods();
mainFrame = (JFrame) constructor.newInstance(myClient);
mainFrame.setSize(width, height);
mainFrame.setLocation(x, y);
if (mustClose)
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public JFrame getFrame() {
return mainFrame;
}
public void invokeMethod(String method) {
for (int i = 0; i < methodList.length; i++) {
if (methodList[i].getName() == method) {
try {
methodList[i].invoke(mainFrame);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
我有反射问题。我将这个类用作各种JFrame元素的通用runnable。出于这个原因,我需要通过反射来调用方法。当我尝试调用某个方法时,出现此错误:Java反射调用不起作用
Exception in thread "main" java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at it.polimi.social.frame.RunnableSupport.invokeMethod(RunnableSupport.java:83)
at it.polimi.social.client.MyClient.main(MyClient.java:56)
即使它看起来没问题。问题是当我尝试调用方法时...我也检查了其他问题,但它们都是不同的问题,即使相似。谢谢!
编辑:我解决了这个问题,谢谢大家。
现在我有关于我所做的事情的另一个问题。为每个JFrame类使用反射而不是具有不同的可运行的runnable是一个好主意吗?我担心的是,每次调用方法时都使用一个类,这意味着要在方法列表中进行搜索。
2015-08-13
Marco
+0
哪一行会引发异常? –
+1
当你调用'invokeMethod()'' –
+0
'时,你的'mainFrame'可能是'null'(因为缓存了不同的线程)'在'invokeMethod'中调用'methodList [i] .invoke(mainFrame);'这引发了NPE。这表明'mainFrame'可能为空。你确定你初始化正确吗?从我看到的你在'run'中初始化它,但你确定'run'将总是在'invokeMethod'之前被调用吗? –