Lazadon
Lazadon

Reputation: 193

dynamically retrieving JUnit class

I would like to instantiate a new class object form external location collected from user input. The program asks the user where the file is, say /tmp/MyTestClass.java. I would then like it to grab that .java file and make it a usable class with in the program. so i could call something like MyClass = new MyTestclass(). I've been looking around and can't seem to find an answer or if its even possible? Any information would be useful.

Thanks!!

-----------EDIT---------------

I may have been over thinking my problem. This is for a JUnit test (sorry should have mentioned this before). Below is an example of what i was using to pull in my static class. I would like to be able to dynamically pull the JUnit test file from user input. testcastjunit was the name of the class. I need to be able to programmaticly get the class from the users input and run the test case.

org.junit.runner.Result result = JUnitCore.runClasses(**testcastjunit.class**);
            for (Failure failure : result.getFailures()) {
                System.out.println(failure.toString());
            }

Upvotes: 1

Views: 339

Answers (2)

Lazadon
Lazadon

Reputation: 193

Thanks to Javier's advise I was able to get my program to dynamically compile and run JUnit Test Cases. I am using this to run Selenium IDE exported .java files. Below is my completed example. Hope this helps anyone else looking for a similar solution. Another note I am using Eclipse IDE for development, Happy coding!

    //the loc and name variables are gathered from user input
    String fileloc = loc +"/"+ name + ".java";
    JavaCompiler jCompiler = ToolProvider.getSystemJavaCompiler();
    List<String> options = Arrays.asList("-d", "./bin/",fileloc);

    int compilationResult = jCompiler.run(null, null, null, 
            options.toArray(new String[options.size()]));
    if (compilationResult == 0){
        //This is the package name exported from selenium IDE exported files
        File file = new File("./bin/com/example/tests/" + name);
        URL url = null;
        try {
            url = file.toURL();
            URL[] urls = {url};
            ClassLoader cl = new URLClassLoader(urls);
            org.junit.runner.Result result = JUnitCore.runClasses(cl.loadClass
                    ("com.example.tests." + name));
            for (Failure failure : result.getFailures()) {
                System.out.println(failure.toString());
            };
        } catch (MalformedURLException e) {
            System.out.println("Error with file location (URL)");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            System.out.println("Couldn't Not Find Test Class To Load");
            e.printStackTrace();
        }
    }else{
        System.out.println("Could not Find Java Source File Located in `" + fileloc + "`");
        System.exit(1);
    }
}

Upvotes: 1

Javier Diaz
Javier Diaz

Reputation: 1830

If I have understood you, this is what you need:

JavaCompiler jCompiler = ToolProvider.getSystemJavaCompiler();
List<String> options = Arrays.asList(
                           "-d", "./bin/",
                           path+".java");
int compilationResult = jCompiler.run(null, null, null, 
                options.toArray(new String[options.size()]));
if (compilationResult == 0) {
    mensaje = "Compiled the "+path+" to its .class";
    ClassLoader cLoader = ClassLoader.getSystemClassLoader();
    try {
        cLoader.loadClass("THE CLASS");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
} else {
    mensaje = "Couldnt compile.";
}

This would work for you:

  1. It gets the java compiler to compile a class.
  2. Creates the options, the -d is wherever you want to put the .class once compiled and the second one is the path of your .java file.
  3. Compiles, and if compilation is successfull it loads the class.
  4. Start using your class!

Upvotes: 4

Related Questions