读书人

Convert Static to Dynamic Construct

发布时间: 2013-03-19 17:22:05 作者: rapoo

Convert Static to Dynamic Construction -- 静态到动态构造转换

Refactoring contributed by Gerard M. Davison

You have classes that have static compile time dependencies on classes that can only be built on a specific platform.

你有一些平台独立的静态编译时期的类

Make use of the java.lang.reflect to break the static dependency.

利用java反射打破静态依赖。

   import org.davison.data.jdbc.JDBCProvider;   .   .   .   DataProvider dp = new JDBCProvider();

Convert Static to Dynamic Construction - 静态到动态结构转换

   try   {      DataProvider dp = (DataProvider)         Class.forName("org.davison.data.jdbc.JDBCProvider").newInstance();   }   catch (IllegalAccessException iae)   {      // Convert exception to error to preseve the interface.      //            throw new IllegalAccessError(iae.getMessage());   }   catch (InstantiationException ie)   {      // Convert exception to error to preseve the interface.      //            throw new InstantiationError(ie.getMessage());         }   catch (ClassNotFoundException cnfe)   {      // Convert exception to error to preseve the interface.      //      throw new NoClassDefFoundError(cnfe.getMessage());   }

Motivation

In some cases you have to provide drivers to provide different functionality depending on the situation. You might have classes that on a given platform need to access some sun.* classes to perform a specific function. For example a class to access WinHelp needs to get the window handle via the sun.awt.windows.WWindowPeer classes.

有时候你会根据情况提供不同功能的驱动程序。

There might also be the desire to only provide certian functionality to a given sub-set of users. This is the equivalent of being able to compile out code without having to alter the source or use pre-compilers.

你可能期望给予用户不同的功能子集,这就相当于不用修改源码或者预编译就能达到这种目的。

This method can be used with good effect with application frameworks where you do not know which class need to be used at compile time.

在应用程序框架中使用反射是一种的好的方式,譬如在编译期你不知道到底需要选择哪个类时。

Mechanics

读书人网 >其他相关

热点推荐