Search code examples
javareflectionconvertersnoclassdeffounderrorcode-conversion

Looking for a Code Converter to Convert a Normal Java Code to Reflection-Style Code


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);

Solution

  • 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.

    The core reflection facility was originally designed for component-based application builder tools... There are a few sophisiticated applications that require reflection. Examples include class browsers, object inspectors, code analysis tools, and interpretive embedded systems... if you have any doubt as to whether you application falls into one of these categories, it probably doesn't.

    Joshua Bloch, "Effective Java", 2nd Edition.