Can I load one of two different classes in java with the same name?
I have a lot of code to call static methods on foo, such as "foo. Method()" I have two different foo implementations and want to use one of them according to the specific situation In pseudocode:
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"); }
Could this be related to Java metaprogramming? I can't load documents completely around all dynamic classes If not, what is the best way to do what I want to do?
Solution
Basically, you have two classes with the same interface but different implementations. Isn't it better to use the interface to do it?
In your main class, build the class environment based on the appropriate instance you use
FooInterface foo; MainClass (FooInteface foo,other fields) { this.foo = foo; } ....
Then use only their foo
Another approach is to use AspectJ in each foo Define a pointcut on the method call. Your if (shouldloadfoo1()) {foo1. Method()} and so on are included in the pointcut suggestions