reflection - Java: Load class from string -


i know has class loaders, couldn't find example (it might i'm google-ing wrong keywords.

i trying load class (or method) form string. string doesn't contain name of class, code class, e.g.

class myclass implements imath {     public int add(int x, int y) {          return x + y;     } } 

and this:

string s = "class myclass implements imath { public int add(int x, int y) { return x + y; }}"; imath loadedclass = something.loadandinitialize(string); int result = loadedclass.add(5,6); 

now obviously, something.loadandinitialize(string) - part 1 don't know how achieve. possible? or easier run javascripts , somehow "give" variables / objects (like x , y)?

thank hints.

use java compiler api. here blog post shows how it.

you can use temporary files this, requires input/output file, or can create custom implementation of javafileobject reads source string. javadoc:

   /**     * file object used represent source coming string.     */    public class javasourcefromstring extends simplejavafileobject {        /**         * source code of "file".         */        final string code;         /**         * constructs new javasourcefromstring.         * @param name name of compilation unit represented file object         * @param code source code compilation unit represented file object         */        javasourcefromstring(string name, string code) {            super(uri.create("string:///" + name.replace('.','/') + kind.source.extension),                  kind.source);            this.code = code;        }         @override        public charsequence getcharcontent(boolean ignoreencodingerrors) {            return code;        }    } 

once have output file (which compiled .class file), can load using urlclassloader follows:

    classloader loader = new urlclassloader(new url[] {myclassfile.tourl());     class myclass = loader.loadclass("my.package.myclass"); 

and instantiate it, using:

    myclass.newinstance(); 

or using constructor.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -