java reflection
The JAVA reflection mechanism is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamically obtained information and dynamic calls The function of the object's method is called the reflection mechanism of the Java language.
Copy the 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()//Method without parameters
{
System.out.println("Hello everyone, my name is "+name+"!");
}
public void say(String str)//method with parameters
{
System.out.println("Hello everyone, my name is "+name+"! "+str+", I am a method with parameters!");
}
}
/**
* @author LXA
* The simplest example of reflection
*/
public classreflection
{
public static void main(String[] args) throws Exception
{
Class c=Class.forName("C_20130313_reflection.User");//Find the corresponding class through reflection
Method m1=c.getMethod("say");//Find the method named say with no parameters
Method m2=c.getMethod("say",String.class);//Find a method named say with a String type parameter
m1.invoke(c.newInstance());//Note that newInstance() calls the parameterless constructor! ! !
m2.invoke(new User("Liu Xian'an"),"Haha");//Instantiate an object through a parameterized construction method
}
}