Java class, as long as you know the class name (full name) You can create its instance object, the general method is to directly use the construction method provided by the class, such as
NewObject o = new NewObject ();
NewObject o = new NewObject ("test");
NewObject o = new NewObject (new string[]{"AAA", "BBB"});
In addition, you can use the java.lang.class<t> class to instantiate Java classes.
1. Empty construction method
If the class has an empty construction method, such as the following class
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);
}
}
The following code can be used for instantiation:
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, with parameter construction method
public class NewObject
{
String name;
Public NewObject ()
{
System.out.println ("The object is created!");
}
public void Write ()
{
System.out.println ("");
}
}
The following code can be used for instantiation:
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, with array parameter construction method
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);
}
}
The following code can be used for instantiation:
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 Object Instantiation