Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to load one of two different classes in Java with the same name?

I have a lot of code that calls static methods on Foo like "Foo.method()". I have two different implementations of Foo and would like to use one or the other depending on the circumstances. In psuedocode:

File Foo1.java

class Foo1 implements Foo {
  public static int method() {
    return 0;
  }
} 

File Foo2.java

class Foo2 implements Foo {
  public static int method() {
    return 1;
  }
}

File Main.java

if(shouldLoadFoo1()) {
  Foo = loadClass("Foo1");
} else {
  Foo = loadClass("Foo2");
}

Is this possible with Java metaprogramming? I can't quite wrap my head around all the dynamic class loading documentation. If not, what's the best way to do what I'm trying to do?

like image 554
Steve Avatar asked Sep 02 '25 01:09

Steve


1 Answers

Essentially you have two classes with the same interface but different implementations,Wouldn't it be better to do it using an interface?

in your main class, depending on the circumstances you would construct your class with the appropriate instance.

FooInterface foo;
MainClass (FooInteface foo, other fields) {
   this.foo = foo;
}


....

then just use foo from them on.

Another way is to use AspectJ, define a point cut on every Foo.method call, in in the advice for the point cut have your if (shouldLoadFoo1()) { Foo1.method()} etc ..

like image 183
hhafez Avatar answered Sep 05 '25 20:09

hhafez