Maana
Maana

Reputation: 700

Java class calling two jars which has same class and method name

EDIT: I have a java class which calls two jars which has same class and method name. Can we implement like this ? how did the JVM know which right class to pick

import com.jar.Myclass; // should go to jar 1
import com.jar.Myclass; // should go to jar 2

public class Test {
public void getDetails(){
  if (true){
    Myclass.getDetails(); // should go and look in jar 1 
 }else {
    Myclass.getDetails(); // should go and look in jar 2 
  }
}

}

Any suggestion on this experts

Upvotes: 0

Views: 480

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308031

Edit: the question has since been edited to ask about two classes with identical FQCN. This answer does NOT apply to this new question.

If the simple name is the same but the package name is different then you should import one and fully quallify each reference to the other, or even fully quallify all references, for simplicities sake:

public class Test {
  public void getDetails(){
     if (true){
      com.jar1.MyClass.getDetails(); // should go and look in jar 1 
    }else {
      com.jar2.MyClass.getDetails(); // should go and look in jar 2 
    }
  }
}

Note that an import does nothing other than providing a simple short name (MyClass) to use instead of the fully-qualified (com.jar1.MyClass). To the runtime itself only the fully qualified class name (FQCN) exist. Imports are purely for the compiler.

Upvotes: 2

Related Questions