Original articles, reproduced please specify.
Reflection can dynamically load classes, instantiate objects, and invoke methods. Now the following example explains.
One. Load class.
Class clazz = Class.forName ("java.lang.String"); This sentence code gets the class object of a string class.
Enter the name of the package.
If through URLClassLoader. Capable of loading local or remote jar packages. And the detailed class object is obtained by the LoadClass method.
Second, instantiate the object.
Assuming that the object is instantiated through the default constructor, we can get an object such as the following method for the class object, such as
Clazz. Newinstance ();
Assuming that an object is instantiated through a constructor with a number of parameters, it can be achieved by, for example, the following code:
constructor<?
> myconstructor = Myclass.getconstructor (parametertypes);//Get a constructor object.
Among them parametertypes for class<?
Parametertypes. Like String.class,int.class and so on. The object is then instantiated through the constructor object:
Myconstructor.newinstance ("xxx", 123); The constructor fills in the detailed construction parameters.
Three. Invokes a method.
Method Mezod = Clazz.getmethod (MethodName, parametertypes), can get the object of the methods class, then we can run the method through the Mezod invoke method.
Mezod.invoke (obj, "xxx", 123);//The first parameter is the initiator of this method, and if NULL is used, it means that the statically static method is called.
A very easy Java Reflection tutorial