Search code examples
javaruntimerxtx

Changing the class file in Runtime


My requirement is to change an import statement in a java file in the runtime. I am accessing a Dot-matrix printer through the COM port and for Windows and Linux I have to use different Jar files - windows com.jar, rxtx.jar. For now I am doing two compilations for two platforms. Below is my class.

import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
//import gnu.io.*;
public class Posmachine {

}

I want to find out if there is a way to change the import jar during runtime which will allow me to check if it's linux or windows and change the classes used in the Posmachine class.


Solution

  • You should create two implementation classes one for each platform. Then get required class via a factory method or object. So you will skip loading the class that depends on the jar that is not available.