lesson:2 处理对象
1.creating objects 【相关文章:发布MSPlus ToolBar&】 【扩展阅读:SQL SERVER 的命名规则】一般情况下,创建一个对象用以下方法 【扩展信息:在vmware上升级linux内核及配置】 rectangle r = new rectangle(); 但如果你正在开发一个development tools,在运行之前或许不知道要生成对象的类。 所以要像下面这样来创建对象: string classname;// . . . load classname from the user interface
object o = new (classname); // wrong!
但以上是错误的。 正确的方法是使用类的反射特性: 1)using no-argument constructors 例如: class classdefinition = class.forname(classname);//指定类的运行期实例 object = classdefinition.newinstance();//调用无参构造函数来生成指定类的实例。2)using constructors that have arguments
这个技术要用到如下步骤: a,创建一个class对象 b,创建一个constructor对象,getconstructor(class[] params)方法,参数是一个与构造方法相适合的class 数组. c,在constructor对象上调用newinstance方法来生成一个对象,参数 是一个object数组与这个构造方法相配备。例如:
import java.lang.reflect.*; import java.awt.*;class sampleinstance {
public static void main(string[] args) {
rectangle rectangle;
class rectangledefinition;class[] intargsclass = new class[] {int.class, int.class};
integer height = new integer(12); integer width = new integer(34); object[] intargs = new object[] {height, width};constructor intargsconstructor;
try {
//1. ... 下一页