首页 > 代码库 > 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(new Object[]{String.class}).newInstance(names);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
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();
}
java对象实例化