Issue
How can I instantiate an object of the class java.lang.Class
from a given .java file?
I want to create an application to automatically generate JUnit tests. For that I would need "Method" objects and for "Method" objects I need to have a "Class" object.
Solution
java 6 onwards has an api for the compiler: http://www.javabeat.net/2007/04/the-java-6-0-compiler-api/
the link above includes an example.
here's another example - http://www.java2s.com/Code/Java/JDK-6/JavaCompilertoolshowyoucancompileaJavasourcefrominsideaJavaprogram.htm
to load the file once compiled you use a classloader. there's an example at http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html and another at http://www.javaworld.com/jw-10-1996/jw-10-indepth.html
you'd think there would be a library to simplify all this. i can't find one, but am still looking.
meanwhile, here's a really nice article from ibm that compiles a function and plots it - http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
found one http://docs.codehaus.org/display/JANINO/Home - this is a library that simplifies the process. i would recommend configuring it to use the javax.tools API (see last sentence in the "what is Janino" paragraph).
sorry for the google snark earlier.
it just struck me that maybe you just want a class object.
if you have a class called MyClass then the associated class is Myclass.class
. that's probably obvious, but perhaps that's all you need.
and if you have the class name in a string you can use this method - http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)
Answered By - andrew cooke
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)