Java反射。运行外部jar并引用它的类? [英] Java Reflection. Running a external jar and referring to its classes?

查看:115
本文介绍了Java反射。运行外部jar并引用它的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码片段允许我在程序中运行一个jar:

  File f = new File 。罐); 
URLClassLoader cl = new URLClassLoader(new URL [] {f.toURI()。toURL(),null});
Class<?> clazz = cl.loadClass(epicurus.Client);
方法main = clazz.getMethod(main,String []。class);
main.invoke(null,new Object [] {new String [] {}});

还有,我可以参考外部程序的类吗?

希望能够更改其JFrame的标题。

解决方案

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



在调用main之后,你需要运行一个循环来访问你感兴趣的窗口(可以在单独的线程)。

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

然后,您可以访问JFrame的字段和方法如果有必要,通过反射来比较jFrame.getName()和一些String)来指定要修改的框架。



例如你感兴趣

 字段textAreaField = jFrame.getClass()。getDeclaredField(textArea) ; 
textAreaField.setAccessible(true);

允许您访问该字段,并允许您以任何您认为合适的方式修改它。 / p>

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

  JTextArea textArea =(JTextArea)textAreaField.get(jFrame); 

Font font = textArea.getFont();
textArea.setFont(new Font(font.getFontName(),font.getStyle(),24));

这应该只是为了你。


This code snippet allows me to run a jar as part of my program:

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[]{}});

Is there anyway that I can refer to that external program's classes?
I want to be able to change the title of its JFrame for instance.

解决方案

I believe you could. I'd attempt as follows.

After invoking the main, you'll want to run a loop to access the Window you're interested in (can be done in a separate thread).

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

You can then access the JFrame's fields and methods (or if necessary, specify that the frame you are modifying is the one you intend by comparing jFrame.getName() and some String) via reflection.

Say for example you are interested in modifying the font size and style in a JTextArea.

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

Would allow you access to the field and permit you to modify it in any way you see fit.

From there you'll need the actual object.

JTextArea textArea = (JTextArea) textAreaField.get(jFrame);

Font font = textArea.getFont();
textArea.setFont(new Font(font.getFontName(), font.getStyle(), 24));

And that should just about do it for you.

这篇关于Java反射。运行外部jar并引用它的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆