Java Reflection
The Java reflection mechanism is in the running state, for any class, all the properties and methods of the class can be known, and any one of its methods and properties can be invoked for any object; This dynamically acquired information, and the function of the method that dynamically invokes the object, is called the reflection mechanism of the Java language.
Copy Code code as follows:
Package c_20130313;
Import Java.lang.reflect.Method;
Class User
{
private String name;
Public User () {}
Public User (String name)
{
This.name=name;
}
public void Say ()//No parameter method
{
System.out.println ("Hello, my name is +name+"!) ");
}
public void Say (String str)//method with parameters
{
System.out.println ("Hello, my name is +name+"!) "+str+", I am a method of participation! ");
}
}
/**
* @author Lxa
* The simplest example of reflection
*/
public class Reflection
{
public static void Main (string[] args) throws Exception
{
Class c=class.forname ("c_20130313_ reflection.") User ");//Find the corresponding class by reflection
Method M1=c.getmethod ("say")//Find the name of the say, and no parameters
Method M2=c.getmethod ("Say", string.class);//Find a way to have a name called Say and have a String type parameter
M1.invoke (C.newinstance ())//Note that newinstance () calls the parameterless construction method!!!
M2.invoke (New User ("Liu Xianhan"), "haha");//Instantiate an object by means of a parameter constructor
}
}