关于动态扩展:在运行时载入类和接口动态扩展我们的程序
java中有两种方式可以实现动态扩展:Class.forName()和java.lang.ClassLoader
请看问题所在:
You often need to modify the behaviour of a program based on external data, such as a command-line parameter. If you hard-code a finite set of acceptable parameter values into a program you will have to modify the program whenever you need to add new parameters. The deployment of new versions will become more complex as the number of installed programs increases. If programs need to interpret parameters in order to interoperate (for example, if the parameters are read from network messages), you must ensure that all users upgrade before they can communicate, which becomes very difficult with large user bases.
解决方法:
Take advantage of Java's built-in(内置的) facilities for dynamic loading and linking of code. Dynamically load and instantiate classes of behaviour corresponding to external parameters.
1.Define an interface through which to access the parameterised behaviour
2.Define a naming scheme that maps user-specified parameters to the name of a Java class.
3.Define classes that implement the interface for various parameters, and follow the naming scheme so that they can be found by the parameter-to-name mapping.
4.At run time, given a parameter value, map it to the name of the Java class that performs the required behaviour.
5.Dynamically load that class using the Class.forName method.
6.Instantiate an object of the class using the Class.newInstance method or via a Constructor of the class.
7.Cast the object to the interface you have defined and pass it to the objects that need to use the parameterised behaviour.
你有一个接口,所有的人都可以实现它,那么这个接口派生的类可能会有无数个,而你的程序又不想(也不可能)把这用到的无数个类声明到你的程序里,重新编译,然后重新启动服务器,这时候就需要动态将Class装载进来。只需要动态提供一个类的包路径,就可以执行该类,这样做最大的好处其实就是动态地处理相同接口的代码.JAVA类或者接口通过一个字符串传给程序,即可以用一个字符串的形式来初始化(映射)一个类!