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元素的通用可运行程序。出于这个原因,我需要通过反射来调用方法。当我尝试调用一个方法时,我得到这个错误:
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类使用不同的可运行程序,这是一个好主意吗?我担心的是,每次调用方法时使用单个类意味着要在方法列表中进行搜索。这一行:
if (methodList[i].getName() == method)
永远不要将字符串与==进行比较。试着把它改成。equals(),看看是否有帮助。