天天看点

Java对象实例化

  newobject o = new newobject();

  newobject o = new newobject(new string[]{"aaa","bbb"});

  除此之外,还可以利用java.lang.class<t>类来实现java类的实例化。

  1、空构造方法

  如果类有空构造方法,如下面的类

public class newobject

{

string name;

public newobject(string[] name)

this.name = name[0];

system.out.println(“ the object is created!”);

}

public void write()

system.out.println(this.name);

  使用以下代码可实现实例化:

newobject no = null;

try

no = (newobject)class.forname(classname).newinstance();

no.write();

catch (instantiationexception e)

e.printstacktrace();

catch (illegalaccessexception e)

catch (classnotfoundexception e)

  2、带参数构造方法

public newobject()

system.out.println(“”);

no=(newobject)class.forname(classname).getconstructor(string.class).newinstance(names);

//no=(newobject)class.forname(classname).getconstructor(newobject[]{string.class}).newinstance(names);

catch(illegalargumentexceptione)

catch(securityexceptione)

catch(instantiationexceptione)

catch(illegalaccessexceptione)

catch(invocationtargetexceptione)

catch(nosuchmethodexceptione)

catch(classnotfoundexceptione)

  3、带数组参数构造方法

  public class newobject

  {

  string name;

  public newobject(string name)

  this.name = name;

  system.out.println(“ the object is created!”);

  }

  public void write()

  system.out.println(this.name);

constructor[] cs;

cs = class.forname(classname).getconstructors();

constructor cc = class.forname(classname).getconstructor(string[].class);

no = (newobject)cc.newinstance(new object[]{names});

catch (securityexception e)

catch (nosuchmethodexception e)

catch (illegalargumentexception e)

catch (invocationtargetexception e)

最新内容请见作者的github页:http://qaseven.github.io/