Alas! I am really in the interview to learn new things Ah, a company just gave a test, but I am very strange is why the web developer position actually test the reflection mechanism of Java, but learning to study the reflection mechanism for me is a good thing!
Let's talk about the Java reflection mechanism, in the running state, all the properties and methods of the class can be known to any class, and any one of its methods can be invoked for any object, and this dynamically acquired information, as well as the function of the method that dynamically invokes the object, is called the reflection mechanism of the Java language. Primary function: To determine at run time the class to which any object belongs, to construct an object of any class at run time, to determine the member variables and methods of any class at run time, to invoke the method of any object at run time, and to generate a dynamic proxy.
Then let's leave an example.
Package com.beidou.test;
Import Java.lang.reflect.Method; public class Dynamic {public static void main (string[] args) throws exception{Class C = dynamic.class;//Get Object Metho
D[] methods = C.getdeclaredmethods ()//Get Method for (methods Method:methods) {System.out.print (Method.getname ());//Print parameter name
class[] parametertypes = Method.getparametertypes ();
for (int i=0;i<parametertypes.length;i++) {String namestring=parametertypes[i].getname (); System.out.print ("ParameterType:" +namestring);//printing method parameter type} System.out.print ("ReturnType:" +method.getreturntype ()
);
System.out.println (); The object Obj=c.newinstance ()///Gets to the method object, assuming that the parameter of the method is a int,string,method named Getage methods SAge = C.getmethod ("Getage", new
Class[] {int.class,string.class});
Gets the parameter Object object[] arguments = new Object[]{new Integer (), New String ("abc")};
Execution method string s= (String) sage.invoke (obj, arguments);
System.out.print (s); Public String getage (int age,string name) {return name+ ":" +age; }
}
Above this Java reflection mechanism---Dynamic invocation of the object is a simple way to share all the content of the people, I hope to give you a reference, but also hope that we support the cloud-dwelling community.