现在关于newInstance的探讨才真正的到了问题的关键, 为什么delphi里有virtual constructor, 这主要是由于delphi的MetaClass的实现方式决定的.
在java和delphi里都支持MetaClass, 但实现的方法不同.
在java中, MetaClass采用反射机制来实现MetaClass, 例如
Class metaClass = forName("MyClass");
MyClass MyObj = (MyClass) metaClass.newInstance();
而delphi是采用class reference和virtual constructor配合来实现的, 例如.
TComponentClass = class of TComponent
..
MyObj : TComponent;
myClass : TComponentClass ;
RegisterClass("MyClass");
..
myClass:= FindComponentClass("MyClass");
MyObj := myClass.Create(nil);
-- override constructor
对于class reference, delphi帮助如下
class reference is an expression that refers to a specific class. A class reference is not quite a first class object, as it is in Java or Smalltalk, but is used to create new objects, call class methods, and test or cast an object's type. A class reference is implemented as a pointer to a table of information about the class, especially the class's virtual method table (VMT).
由上我们可看出, delphi不象java 或C#, 他不是基于VM的, 所以他不可以象java通过JVM来帮助实现反射, 对与class reference和virtual constructor配合的方法好坏, 我不好评说, 但基于VM的运行语言已成为趋势, delphi.net已经在利用.net的特性, 完成了这个飞跃.
另外, JVM和.net的VM也有很大不同, 下面是他们在执行中的主要区别.
Executing interpreted code means: for each opcode in the input stream,
collect the parameters to the opcode and call a chunk of native code to
perform the operation represented by the opcode. Think of it as a giant
case statement inside the interpreter. Every time execution passes through
an interpreted function, the meaning of the opcode is evalutated anew.
Executing native compiled code means: each opcode in the input stream is
recognized by the CPU hardware and the operation corresponding to the
symbolic opcode is performed by the CPU hardware.
.NET IL bytecode is compiled into native machine code when it is loaded from
disk into memory. .NET applications run native compiled code.
.NET is different from Java in that Java was first designed to be
interpreted, and later Just In Time compilation was added. Even in a fully
"JIT'd" Java platform, there exists a Java bytecode interpreter somewhere in
the VM. In .NET, there is no IL bytecode execution interpreter. .NET IL
code is always compiled to native code before it executes.
The compiler you refer to is part of the program loader. You compile your
Delphi source code into a .NET executable using the Delphi for .NET
compiler. You then
run your .NET program Hello.exe, and the program loader
takes care of "compiling" the machine-independent .NET code in your program
into native machine code as your program makes calls to subroutines.
The advantage of this approach is that your Hello.exe program has the
potential to run on different CPU architectures - Intel 32 or 64 bit, AMD 64
bit, Motorolla, even Fujitsu mainframes.