"0" README
0.1) This article describes + source code is transferred from http://blog.csdn.net/fenglibing/article/details/4531033, in order to deeply understand how to use reflection mechanism to create class instances;
0.2) reproduced in the source code, see https://github.com/pacosonTang/core-java-volume/tree/master/chapter5/ Reflectioncreateinstance "1" creates a new class example from reflection, in two ways:
2.1 The first way: class.newinstance ()
2.2 The second way: constructor.newinstance () "2" to the following two ways to give a comparison description:
2.1 The constructor invoked has no parameters: class.newinstance () can only call parameterless constructors, that is, the default constructor, and Constructor.newinstance () can, depending on the parameters passed in, Call any constructor (including a parameter + no parameter);
2.2 Throws an exception: class.newinstance () throws all exceptions thrown by the called constructor;
2.3 The visibility of the constructor invoked: Class.newinstance () requires that the invoked constructor be visible and must be of public type; constructor.newinstance () in a particular case, You can call a private constructor (private); "3" Look at a litchi .
3.1) A.java
Package com.corejava.chapter5;
public Class A
{
private A ()
{
System.out.println ("a" s constructor is called.);
}
Private A (int a, int b)
{
System.out.println ("A:" + A + "B:" + b);
}
3.2) B.java
Package com.corejava.chapter5;
Import Java.lang.reflect.Constructor;
Import static java.lang.System.out;
public class B {public static void main (string[] args) {b b;
b = new B ();
OUT.PRINTLN ("Call private constructor via Class.newinstance ():");
B.newinstancebyclassnewinstance ();
OUT.PRINTLN ("Call private constructor via Constructor.newinstance ():");
B.newinstancebyconstructornewinstance ();
}/* Create a new class sample via Class.newinstance ()/* private void Newinstancebyclassnewinstance () {try {
/* The current package name is reflect and must use the full path/a = (a) class.forname ("com.corejava.chapter5.a"). newinstance ();
The catch (Exception e) {out.println () calls the private constructor "failed" by Class.newinstance ());
}/* Create a new class sample via Constructor.newinstance () * * private void newinstancebyconstructornewinstance () { try {/* can use a relative path, which can be used without a package path in the same package/Class C = Class.forName ("Com.corejava.chapteR5.
A ");
/* The following calls the parameterless, private constructor/constructor C0 = C.getdeclaredconstructor ();
C0.setaccessible (TRUE);
A a0 = (a) c0.newinstance ();
/* The following call with the parameter, private constructor/Constructor C1 = C.getdeclaredconstructor (new class[] {int.class,int.class});
C1.setaccessible (TRUE);
A a1 = (a) c1.newinstance (new object[] {5, 6});
catch (Exception e) {e.printstacktrace (); }
}
}