在学习Java教程的时候,Reflection和Late Binding让我很困惑。在一些教程中,他们写道它们是相同的,并且反射和后期绑定(bind)之间没有任何区别。但是其他教程说有区别。
我很困惑,所以有人可以解释一下 Java 中的反射和后期绑定(bind)是什么,如果可能的话,请给我一些关于两者的真实示例。
谢谢..
最佳答案
Java 使用后期绑定(bind)来支持多态性;这意味着应该推迟到运行时才决定应该使用许多方法中的哪一个。
以 N 个类实现接口(interface)(或抽象类,fwiw)的抽象方法为例。
public interface IMyInterface {
public void doSomething();
}
public class MyClassA implements IMyInterface {
public void doSomething(){ ... }
}
public class MyClassB implements IMyInterface {
public void doSomething(){ ... }
}
public class Caller {
public void doCall(IMyInterface i){
// which implementation of doSomething is called?
// it depends on the type of i: this is late binding
i.doSomething();
}
}
反射被用来描述能够检查其他代码的代码,即。知道类中有哪些方法或属性可用,按名称调用方法(或加载类),并在运行时做很多非常有趣的事情。
反射的一个很好的解释在这里:What is reflection and why is it useful?
关于java - java中反射和后期绑定(bind)的区别与实时示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8984633/