0

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 ?

3
  • Why would you want to do something like that? Commented Apr 17, 2020 at 9:20
  • @Amongalen I am building a RMI application and I want to send the .class file from the server to the client. Commented Apr 17, 2020 at 9:22
  • 2
    You are trying to solve a problem that doesn’t exist. You can compile your ExampleClass using the Operation.class, just as you want, without any problems. There is no requirement to have the source code of Operation available. That’s how you compile your code against the JDK classes, as well as 3rd party libraries, without the need to have their source code at hand. Commented Jun 22, 2020 at 10:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Did you test that this code works ? It doesn't for me. First thing first : A is undefined.
@ROBlackSnail A is a placeholder. In your example, you should replace it with Operation.
@ROBlackSnail Oh I'm sorry that part of the code was copied by mistake. i deleted it. the part in try block is the answer.
@ROBlackSnail Yes, you can do that with relection. read Using Java Reflection.
@ROBlackSnail and read Reflection in Java.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.