reflection - Java - Adding Functionality by Adding a New Class Without Modifying Anything Else -
how possible have classes a
, b
, c
, functionality f, , add together class d
bin/
, different functionality f without modifying a
, b
or c
in way?
i've seen done in modloader minecraft. modloader, re-create classes on modloader minecraft. can drop new class starts "mod_" minecraft jar , adds new things game. @ no point there classes reference "mod_foobar" class directly.
a little working example, , links farther reading preferable.
public class reflection { public void sayhello(string theclass){ //since mod classes in bundle 'mod', precede name accordingly. class aclass = class.forname("mod." + theclass); aclass.getmethod("sayhi").invoke(aclass.newinstance()); } public static void main(string[] args) { //get list of compiled classes in 'mod' folder string path = "./bin/mod"; string filename; file folder = new file(path); list<file> filelist = arrays.aslist(folder.listfiles()); //iterate through list of classes invoke methods iterator<file> = filelist.iterator(); while(it.hasnext()){ filename = it.next().getname(); //when invoking sayhello method, remove file extension new reflection().sayhello(filename.replace(".class", "")); } } }
class moda:
public class moda { public void sayhi(){ system.out.println("hi! i'm moda."); } }
class modb:
public class modb { public void sayhi(){ system.out.println("hi! i'm modb."); } }
please note:
i've removed necessary exception handling in order clarify example. the mod classes located in bundle called 'mod'. after compilation, nowadays in bin/mod. there might cleaner way of scanning them. the mod classes compiled, packed jar , included in build path. java reflection
No comments:
Post a Comment