Java反思。 运行外部jar并引用它的类?

这段代码片段允许我在我的程序中运行jar:

File f = new File("client.jar"); URLClassLoader cl = new URLClassLoader(new URL[]{f.toURI().toURL(), null}); Class clazz = cl.loadClass("epicurus.Client"); Method main = clazz.getMethod("main", String[].class); main.invoke(null, new Object[]{new String[]{}}); 

无论如何,我可以参考那个外部程序的类吗?
我希望能够更改其JFrame的标题。

我相信你可以。 我尝试如下。

在调用main之后,您将需要运行一个循环来访问您感兴趣的Window(可以在单独的线程中完成)。

 for(Window window : Window.getWindows()){ if(window != null && window.isVisible() && window instanceof JFrame){ JFrame jFrame = (JFrame)window; } } 

然后,您可以通过reflection访问JFrame的字段和方法(或者,如果需要,通过比较jFrame.getName()和某些String来指定要修改的帧是您想要的帧)。

比如说您有兴趣修改JTextArea中的字体大小和样式。

 Field textAreaField = jFrame.getClass().getDeclaredField("textArea"); textAreaField.setAccessible(true); 

允许您访问该字段并允许您以您认为合适的任何方式对其进行修改。

从那里你需要实际的对象。

 JTextArea textArea = (JTextArea) textAreaField.get(jFrame); Font font = textArea.getFont(); textArea.setFont(new Font(font.getFontName(), font.getStyle(), 24)); 

这应该就是为你做的。