寻找代码转换器将普通Java代码转换为反射式代码

我正在寻找一个转换器来从普通的
Java代码生成反射式
Java代码.我这样做是为了防止像NoClassDefFoundError这样的异常(我想依赖于一个类,但是如果我使用的库没有那个依赖类,我希望Java简单地忽略代码).

我希望转换器像这样:

初始代码:

com.foo.MyClass myClass = new com.foo.MyClass()
myClass.meth1();

转换后:

Object myClass = Class.forName("com.foo.MyClass").newInstance();
myClass.getMethods("meth1").invoke(myClass);

最佳答案 您应该尽可能地避免在Java代码中使用反射.您可以使用其他方法,例如
@mwittrock建议的方法,以避免获取NoClassDefFoundError.

您可以使用反射解决问题,但您可能会在设计中引入新问题.考虑性能成本以及反射代码的详细程度.

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”,第2版.

点赞