I have a project which can contain a lot of modules. Each module is stored in a single class
file. But when I deliver the software to the customers, it is not clear which modules they will need in the future.
Is it possible to deliver class
NewClass to my customer and he can call a method from it without changing the code of the existing program?
He could type the name of the class
in a field, so the program would know which class
to use. And all the methods names are same in all the added class
es.
I guess it could work with Javassist, but I did not find a good tutorial for it.
I would like to call method m1() from NewClass.
class NewClass implements MyModule {
@Override
public void m1() {
// do something
}
}
CodePudding user response:
Sure. What you're looking for is the reflection API.
For example:
String cName = askUserForClass();
assert cName.equals("com.foo.schreiber.PriceyModule");
Class<?> moduleClass = Class.forName(cName);
MyModule mm = (MyModule) moduleClass.getConstructor().newInstance();
and now you have a variable of type MyModule. You can just invoke m1
on this, assuming m1
is in MyModule
and MyModule
is in the base version (that's how you should be setting this up).
Note, of course, that com.foo.schreiber.PriceyModule
does need to be on the classpath of the JVM for this to work. If it is not, this answer is going to grow about 3 pages worth, to set up a class loader, set up loading parentages so that you share the MyModule
definition, and a whole lotta code to reliably find the jar or whatever it might be that is the source of the extra module. So, you know. Would be a lot simpler if you can just ensure it's on the classpath. As long as its in the jar, that'll be the case.