Sample Java reflection mechanism
- 2020-04-01 03:20:18
- OfStack
Java reflection
JAVA reflection mechanism is in the running state, for any class, can know all the attributes and methods of the class; For any object, you can call any of its methods and properties. This ability to dynamically retrieve information and dynamically invoke methods on objects is called the Java language's reflection mechanism.
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 arguments
{
System.out.println(" Hello, everyone, I call "+name+" ! ");
}
public void say(String str)//Method with arguments
{
System.out.println(" Hello, everyone, I call "+name+" ! "+str+" , I am Method with arguments ! ");
}
}
/**
* @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 a name called say and No arguments
Method m2=c.getMethod("say",String.class);//Find a method called say with a string-type argument
m1.invoke(c.newInstance());//Note that newInstance() calls the construction method without arguments!!
m2.invoke(new User(" Liu Xianan ")," Ha ha ");//Instantiates an object through a constructor with arguments
}
}