Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to "reset" a class loader?
    primarykey
    data
    text
    <p><strong>I have to dynamically load a class with the same name from some JAR, but different implementation, multiple times.</strong></p> <p>I'm creating an evaluator backend and I have to dynamically load classes and test them.</p> <p>The tests are JUnit classes that instantiate the classes which should be tested, this is a simple example:</p> <pre><code>package evaluator.tests; import static org.junit.Assert.*; import org.junit.*; import evaluator.tested.*; public class KTest { private K tested; @Before public void setup() { tested = new K(); } @Test public void returnsTrueTest() { assertTrue(tested.returnsTrue()); } } </code></pre> <p>The rest of my application would need to receive JAR files from users which would contain implementations of the <code>K</code> class which is being tested above. Then, <code>KTest</code> would have to run on <em>their</em> <code>K</code> classes, not the ones in the application.</p> <p>I know how to dynamically load a class, but I don't know how to make a test work with it, and not the one which I made.</p> <p>One of the solutions I came up with was to isolate testing in a completely new class, e.g. <code>Evaluation</code>, create a new <strong>class loader</strong> in that class, and make it load all referenced classes. After creating the class loader, it would load the <code>K</code> class from the JAR file.</p> <p>This would mean that each time a user submits his JAR, a separate <code>Evaluation</code> would be instantiated, it would create its own class loader and start the JUnit test. When that happens, the test would use the user's implementation of <code>K</code>, <em>and not the default one</em>.</p> <p><strong>Is this possible, and how can it be done?</strong></p> <p>I read that class loaders always ask their parent whether a class is already loaded. This would mean that I would have to somehow "flush" all the classes that I loaded dynamically from the JAR file in <code>Evaluation</code>, so that they would be unloaded and then loaded again in another <code>Evaluation</code>.</p> <p>Load class <code>K</code>, test class <code>K</code>, unload class <code>K</code>, repeat with different <code>K</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload