Java对象实例化

Java对象实例化

 JAVA类,只要知道了类名(全名)就可以创建其实例对象,通用的方法是直接使用该类提供的构造方法,如
  NewObject o = new NewObject();
  NewObject o = new NewObject("test");
  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)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}

字体:        | 上一篇 下一篇 | 打印  | 我要投稿 

  2、带参数构造方法
public class NewObject
{
String name;
public NewObject()
{
System.out.println(“ the object is created!”);
}
public void write()
{
System.out.println(“”);
}
}
  使用以下代码可实现实例化:
try
{
no=(NewObject)Class.forName(className).getConstructor(String.class).newInstance(names);
//no=(NewObject)Class.forName(className).getConstructor(newObject[]{String.class}).newInstance(names);
}
catch(IllegalArgumentExceptione)
{
e.printStackTrace();
}
catch(SecurityExceptione)
{
e.printStackTrace();
}
catch(InstantiationExceptione)
{
e.printStackTrace();
}
catch(IllegalAccessExceptione)
{
e.printStackTrace();
}
catch(InvocationTargetExceptione)
{
e.printStackTrace();
}
catch(NoSuchMethodExceptione)
{
e.printStackTrace();
}
catch(ClassNotFoundExceptione)
{
e.printStackTrace();
}
  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);
  }
  }
  使用以下代码可实现实例化:
try
{
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)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。