Java Reflection. Running a external jar and referr

2019-03-02 08:25发布

问题:

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.

回答1:

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.