java - Loading a static method using custom class loader -


i've custom class loader follows

import java.lang.reflect.constructor; import java.lang.reflect.method;  public class myclassloader extends classloader {     public string invoke(final string classname, final string methodname, final string somestring)     {         try {             final classloader classloader = getclass().getclassloader();             final class loadedclass = classloader.loadclass(classname);             final constructor constructor = loadedclass.getconstructor();             final object myclassobject = constructor.newinstance();             final method method = loadedclass.getmethod(methodname, string.class);             final object teststr = method.invoke(myclassobject, somestring);             system.out.println(loadedclass.getclassloader());             return (string) teststr;         }         catch (final classnotfoundexception e) {             e.printstacktrace();         }         catch (final exception e) {             e.printstacktrace();         }         return null;     } } 

and class named bus

public class bus {     public static string connection(final string incoming)     {         return "bus " + incoming;     } } 

and tester class test code

public class tester {      public static void main(final string[] args) throws interruptedexception     {         (int = 0; < 3; i++) {             final myclassloader mcl = new myclassloader();             final string s = mcl.invoke("bus", "connection", "awesome");             system.out.println("tester: " + s);             thread.sleep(300);         }     } } 

question: why sysout inside myclassloader print same object (a.k.a class loader)? doing wrong?

what want achieve each iteration in tester class, bus class loaded new class loader

you need implement own class loader rather use system class loader. here rather trivial way works if class file in expected directory.

public class myclassloader extends classloader {     @override     public class<?> loadclass(string name) throws classnotfoundexception {         try {             byte b[] = files.readallbytes(paths.get("target/classes/"+name+".class"));             bytebuffer bb = bytebuffer.wrap(b);              return super.defineclass(name, bb,null);         } catch (ioexception ex) {             return super.loadclass(name);         }     }       public string invoke(final string classname, final string methodname, final string somestring)     {         try {             final classloader classloader = this; 

...


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -