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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>