我有很多这样的例子
Foo.a()
但现在我想根据某些条件拆分对 a() 的调用。如果可能的话,我想保持 Foo.a() 调用不变。相反,也许 Foo 可以成为一个管理流程的工厂,而 FooA 和 FooB 可以扩展 Foo。例如,在 Foo 中:
private static Class<?> foo;
static {
if (certain_criteria) {
foo = SomeUtil.getClass("FooA");
} else {
foo = FooB.class;
}
Object obj = foo.newInstance();
o = (Foo) obj;
}
...
public static void a() {
o.a(); //And this should call either FooA.a() or FooB.a()
//But a() should be accessed in a static way
}
我无法将 Foo 中的 a() 设为非静态,因为那样我就必须将整个项目中的 100 多个调用更改为 Foo.a()。有没有解决的办法?或者更好的处理流程的方法?
我还尝试使用 foo 来调用 a(),但这会产生编译器错误,因为它是 Class 类型?>。如果我将其更改为
Class<Foo>
然后我明白了
Type mismatch: cannot convert from Class<FooB> to Class<Foo>
最佳答案
您建议使用静态方法Foo.a()
作为选择和调用适当实现的外观,以类Foo
选择的可配置方式。您的具体想法似乎依赖于 Foo
的子类实现支持Foo.a()
的策略模式.
您将至少两个可分离的部分与此合并:
- 实现策略
Foo.a()
,并且 - 选择和实例化特定策略的机制。
特别是,尽管您可能有理由想要使用 Foo
的子类为了在真实代码中表示您的策略,您的示例代码中没有明显的原因。那么,从原理上讲,您似乎想要这样的东西:
public class Foo {
private static FooStrategy strategy = FooStrategyFactory.createStrategy();
public static void a() {
strategy.doA();
}
}
interface FooStrategy {
void doA();
}
当然,您不需要一路走到那里。你最初的想法基本上是让 Foo
其本身代替FooStrategy
,并让静态初始化程序代替单独的 FooStrategyFactory
服务。这本质上并没有什么问题;我只是将其拆开,以更清楚地显示每个部分的作用。
您还表达了一些具体的实现问题:
If I change it to
Class<Foo>
then I getblock 引用>Type mismatch: cannot convert from Class to Class
上面的方案中的等效内容是声明
Class<FooStrategy>
类型的变量,并尝试为其分配Class<FooStrategyA>
表示实现FooStrategy
的类。Class
的正确类型可以表示其实例与类型FooStrategy
赋值兼容的任何类的对象是Class<? extends FooStrategy>
。这是否有效FooStrategy
本身是一个类或接口(interface)。I can't call any classes from Foo on foo. "The method a() is undefined for the type Class"
您似乎一直在说您无法调用类
Foo
的静态方法在Class<? extends Foo>
类型的对象上。事实上,你不能。类的对象Class
只有类Class
的方法。尽管您可以使用它们来反射性地调用它们所代表的类的方法,但这些方法不能通过Class
直接访问。实例本身。这个问题不会直接出现在我提出的方案中,但可能会出现在工厂或策略实现中。此外,静态方法不是虚拟的。它们在编译时根据调用它们的引用表达式的形式类型进行绑定(bind)。为了正确应用策略模式,所需的策略实现方法需要是虚拟的:非
private
和非static
.
关于java - 静态调用的变更流程(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553744/