well! I'm really learning something new in the interview. A company just gave a test, but I'm very surprised why the position of web developer actually took the Java reflection mechanism question, but it's a good thing for me to learn and study the reflection mechanism!
Let’s talk about what the java reflection mechanism is. 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 method of its dynamically obtained information and the function of dynamically calling the object methods are called the reflection mechanism of the java language. Main functions: judge the class to which any object belongs at runtime; construct the objects of any class at runtime; judge the member variables and methods of any class at runtime; call the methods of any object at runtime; generate dynamic proxy.
Then leave another 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 the object Method[] methods = c.getDeclaredMethods();//Get the method for(Method method: methods){ System.out.print(method.getName());//Print the parameter name Class[] parameterTypes = method.getParameterTypes(); for(int i=0;i<parameterTypes.length;i++){ String nameString=parameterTypes[i].getName(); System.out.print("parameterType:"+nameString);//Print method parameter type} System.out.print("ReturnType:"+method.getReturnType()); System.out.println(); } Object obj=c.newInstance();//Get the method object, assuming that the parameter of the method is an int,String, method is called getAge Method sAge = c.getMethod("getAge", new Class[] {int.class,String.class}); //Get parameters Object Object[] arguments = new Object[]{new Integer(23),new String("abc")}; //Execute method String s=(String)sAge.invoke(obj, arguments); System.out.print(s); } public String getAge(int age,String name){ return name+": "+age; }}The above Java reflection mechanism - the simple method of dynamically calling objects is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.