什么是在java中调度

thu*_*nja 19 java

我对确切的调度感到困惑.特别是在双重调度方面.有一种简单的方法可以把握这个概念吗?

Mik*_*uel 35

Dispatch是语言链接调用函数/方法定义的方式.

在java中,一个类可能有多个具有相同名称但参数类型不同的方法,并且该语言指定使用具有实际参数可以匹配的最具体类型的正确数量的参数将方法调用分派给该方法.这是静态派遣.

例如,

void foo(String s) { ... }
void foo(Object o) { ... }
{ foo("");           }  // statically dispatched to foo(String)
{ foo(new Object()); }  // statically dispatched to foo(Object)
{ foo((Object) "");  }  // statically dispatched to foo(Object)
Run Code Online (Sandbox Code Playgroud)

Java也有虚拟方法调度.子类可以覆盖在超类中声明的方法.因此,在运行时,JVM必须将方法调用分派给适合于运行时类型的方法版本this.

例如,

class Base { void foo() { ... } }
class Derived extends Base { @Override void foo() { ... } }


{ new Derived().foo(); }  // Dynamically dispatched to Derived.foo.
{
  Base x = new Base();
  x.foo();                // Dynamically dispatched to Base.foo.
  x = new Derived();      // x's static type is still Base.
  x.foo();                // Dynamically dispatched to Derived.foo.
}
Run Code Online (Sandbox Code Playgroud)

Double-dispatch静态运行时(也称为动态)调度的组合.