javaimportcompilation.class-file

Java - Compile using .class file


I have the following java class:

public class ExampleClass{

    public static void main(String[] args){
        Operation op1 = new Operation();
    }
}

And then in another location I have this class:

public class Operation{
    public int value;
}

Is it possible to create a new Operation object in ExampleClass WITHOUT directly importing Operation in ExampleClass. I want to compile de Operation.java, then copy the resulted Operation.class file to the location of ExampleClass and use this file to compile ExampleClass.java. Is such a thing possible ?


Solution

  • You can get new instance of Operation by reflection without import it in code.

    try {
        Class.forName("package.Operation").getConstructor().newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    replace package.Operation with the package of Operation class.