Summary of java reflection mechanism (super detailed)

The reflection mechanism of Java means that in the running state of the program, objects of any class can be constructed, the class to which any object belongs, the member variables and methods of any class can be known, and the method of any object can be called. properties and methods. This function of dynamically obtaining program information and dynamically calling objects is called the reflection mechanism of the Java language. Reflection is considered the key to dynamic languages.

1.1 Three ways to get class

The first:

	Class c = Class.forName("完整类名");//包括所在包						 

The second type:

	Class c = 对象.getClass();

The third type:

	Class c = int.class;

	Class c = String.class;

1.2 Get properties

//获得public属性
Field f1 = c.getField("service1");
//获得全部属性(包括私有属性)
c.getDeclaredFields();

1.3 Obtaining methods and modifiers, parameters

//获取去类中的所有方法,返回一个method数组
Method[] methods = c.getDeclaredMethods();
//获取当前方法的修饰符参数
int modifiers = method.getModifiers();
//通过"Modifiers.	PUBLIC"可以指定修饰符
//获取该方法的参数
Class<?>[] types= method.getParameterTypes();

1.4 invoke implements method call

invoke(Object obj, Object... args) is a method in the method class, this method is a native method

obj: the instance object of the calling class

args: The parameters of calling the sending method are of variable length

Method.invoke(obj, args) can be used to call the method method, and pass parameters through the args parameter.

1.5 Get the annotation on the specified class

System.out.println(Arrays.toString(c.getAnnotations()));

1.6 Determine whether an annotation has been added to the type, method, or attribute

System.out.println(c.isAnnotationPresent(Table.class));

1.7 Get the parameters of the annotation through the instance of the annotation

Table instance = c.getAnnotation(Table.class);
System.out.println(instance.value());

1.8 Obtain the value of the attribute by obtaining the attribute

CustomerController c1 = new CustomerController();
c1.setUserName("Demo");
Class<?> clazz = CustomerController.class;
//得到属性名为username的属性
Field userName = clazz.getDeclaredField("userName");
//方法为private时一定要添加setAccessible
userName.setAccessible(true);
//获得该属性的值
System.out.println(userName.get(c1)); // Demo

1.9 newInstance creates an instance

Object instance = clazz.newInstance();
//经常与invoke搭配使用,实现方法的调用
...method.invoke(instance,...);

Guess you like

Origin blog.csdn.net/ILIKETANGBOHU/article/details/127205040