[Java advanced] reflection learning two-reflection

1. Getting started with reflection

There are such objects in the method area called class objects . They represent all the classes we write. When we create new objects, we will create instances for us based on these class objects and call their construction methods.

The JAVA reflection mechanism is in the running state , for any class, you can know all the attributes and methods of this class ; for any object, you can call any of its methods and attributes; this kind of dynamically acquired information and dynamic calls The function of the method of the object is called the reflection mechanism of the java language.

Simply put: a class has multiple components, such as: member variables, methods, construction methods, etc. Reflection is to load the class and dissect the various components of the class .

The Java reflection mechanism mainly provides the following functions:

  • Judge the class to which any object belongs at runtime;
  • Construct an object of any class at runtime;
  • Judge the member variables and methods of any class at runtime;
  • Call any object method at runtime; generate dynamic proxy

Two, reflection API introduction

Brief description: All the classes we write will be loaded into the method area of ​​JVM memory by AppClassLoader to generate an object of type Class . They are all classes you wrote, but at the same time they are also instances of Class. It is also called an instruction manual.

Class is called the manual of the manual, it tells us how to write the manual, for example, it can have methods, attributes, etc.

Our classes are all manuals, which explain the methods and properties of a certain thing.

There are not many classes required for Java reflection, mainly including the java.lang.Class class and the Field, Constructor, Method, and Annotation classes in the java.lang.reflect package . Note: The Class class is the origin of Java reflection. For any class you want to explore, you must first generate a Class object for it, and then you can obtain other desired information through the Class object .

1. The method of obtaining class objects

1、使用类
Class clazz = Dog.class;

2、使用全类名
Class aClass = Class.forName("com.xinzhi.Day");

3、使用对象
Dog dog = new Dog();
Class clazz = dog.getClass();

2. Operate on class objects

//获取类名字
String name = clazz.getName();
//获取类加载器
ClassLoader classLoader = clazz.getClassLoader();
//获取资源
URL resource = clazz.getResource("");
//得到父类
Class superclass = clazz.getSuperclass();
//判断一个类是不是接口,数组等等
boolean array = clazz.isArray();
boolean anInterface = clazz.isInterface();

//重点,使用class对象实例化一个对象
Object instance = clazz.newInstance();

3. Get the field and operate

Field

(1) Get fields

//获取字段,只能获取公共的字段(public)
Field name = clazz.getField("type");
Field[] fields = clazz.getFields();
//能获取所有的字段包括private
Field color = clazz.getDeclaredField("color");
Field[] fields = clazz.getDeclaredFields();

System.out.println(color.getType());

(2) Get the properties of the object

Dog dog = new Dog();
dog.setColor("red");
Class clazz = Dog.class;
Field color = clazz.getDeclaredField("color");
System.out.println(color.get(dog));

Of course, if you know the type, you can also use the following methods,

Int i = age.getInt(dog);
xxx.getDouble(dog);
xxx.getFloat(dog);
xxx.getBoolean(dog);
xxx.getChar(dog);
//每一种基本类型都有对应方法

(3) Set the properties of the object

Dog dog = new Dog();
dog.setColor("red");
Class clazz = Dog.class;
Field color = clazz.getDeclaredField("color");
color.set(dog,"blue");
System.out.println(dog.getColor());

Of course, if you know the corresponding type, we can do this

xxx.setBoolean(dog,true);
xxx.getDouble(dog,1.2);
xxx.getFloat(dog,1.2F);
xxx.getChar(dog,'A');
//每一种基本类型包装类都有对应方法

 

Field color = dogClass.getDeclaredField("color");
//暴力注入
color.setAccessible(true);
color.set(dog,"red");

3. Method

(1) How to obtain

//根据名字和参数类型获取一个方法
Method method = clazz.getMethod("eat",String.class);
Method[] methods = clazz.getMethods();

Method eat = clazz.getDeclaredMethod("eat", String.class);
Method[] declaredMethods = clazz.getDeclaredMethods();

(2) Operation of the method

Dog dog = new Dog();
dog.setColor("red");
Class clazz = Dog.class;
//获取某个方法,名字,后边是参数类型
Method method = clazz.getMethod("eat",String.class);
//拿到参数的个数
int parameterCount = method.getParameterCount();
//拿到方法的名字
String name = method.getName();
//拿到参数的类型数组
Class<?>[] parameterTypes = method.getParameterTypes();
//拿到返回值类型
Class<?> returnType = method.getReturnType();
//重点。反射调用方法,传一个实例,和参数
method.invoke(dog,"热狗");

 

        Class dogClass = Class.forName("com.xinzhi.Dog");
        Object dog = dogClass.newInstance();

        Method eat = dogClass.getMethod("eat");
        eat.invoke(dog);

        Method eat2 = dogClass.getMethod("eat",String.class);
        eat2.invoke(dog,"meat");

        Method eat3 = dogClass.getMethod("eat",String.class,int.class);
        eat3.invoke(dog,"meat",12);

4. Constructor

(1) Obtain and construct objects

Constructor[] constructors = clazz.getConstructors();
Constructor constructor = clazz.getConstructor();
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
Constructor declaredConstructor = clazz.getDeclaredConstructor();


Object obj = constructor.newInstance();

5. Annotation

Note: If you are not familiar with annotations, you can take a look first: [Java Advanced] Reflection Learning One-Annotations

(1) Obtain annotations from methods, fields, and classes

//元注解 要加上runtime
//类上
Annotation annotation = clazz.getAnnotation(Bean.class);
Annotation[] annotations = clazz.getAnnotations();

//字段上
Annotation annotation = field.getAnnotation(Bean.class);
Annotation[] annotations = field.getAnnotations();

//方法上
Annotation annotation = method.getAnnotation(Bean.class);
Annotation[] annotations = method.getAnnotations();

Link: https://www.jianshu.com/p/87a2731aaf2f

●The strongest Tomcat8 performance optimization in history

Why can Alibaba resist 10 billion in 90 seconds? --The evolution of server-side high-concurrency distributed architecture

B2B e-commerce platform--ChinaPay UnionPay electronic payment function

Learn Zookeeper distributed lock, let interviewers look at you with admiration

SpringCloud e-commerce spike microservice-Redisson distributed lock solution

Check out more good articles, enter the official account--please me--excellent in the past

A deep and soulful public account 0.0

Guess you like

Origin blog.csdn.net/a1036645146/article/details/111032215