I’m looking for a converter to make a reflection-style Java code from a normal Java code. I’m doing this to prevent exceptions like NoClassDefFoundError (I want to be dependent to a class, but I want Java to simply ignore the code if the library I’m using doesn’t have that dependency class).
I expect converter like this:
initial code:
com.foo.MyClass myClass = new com.foo.MyClass()
myClass.meth1();
after conversion:
Object myClass = Class.forName("com.foo.MyClass").newInstance();
myClass.getMethods("meth1").invoke(myClass);
You should try to avoid the use of reflection in your java code as much as you can. You can use other approaches, like the one suggested by , @mwittrock to avoid getting those
NoClassDefFoundError.You might be able to solve a problem using reflection, but you’re likely to introduce new ones in your design. Consider the performance cost as well as the verbosity of the reflection code.
Joshua Bloch, “Effective Java”, 2nd Edition.