What is Java reflection? Detailed introduction to Java reflection mechanism
This article brings you what is Java reflection? The detailed introduction of Java reflection mechanism has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Concept
Java reflection (Reflection) means that when a Java program is running, it can load a class whose name is known only, obtain the complete construction method of the class, and instantiate the object, giving Set values for object properties or call object methods. This function of dynamically obtaining class information and dynamically calling object methods at runtime is called Java's reflection mechanism.
2. Class class
The Class class inherits from the Object class and is the entrance to the Java reflection mechanism. It encapsulates the runtime information of a class or interface and can be obtained by calling the method of the Class class. these messages. How to understand this Class class? If an ordinary class is a collection of all object methods and attributes, then this Class class can be understood as a collection of all ordinary classes.
The following are several methods of obtaining the Class class:
public class TestClass { public static void main(String[] args) throws ClassNotFoundException { // 1、 Class.forName(); Class<?> aClass0 = Class.forName("java.lang.Object"); // 2、类名.Class Class<Integer> aClass1 = Integer.class; // 3、包装类.TYPE —— 返回基本类型的 Class 引用,基本类型在虚拟机运行时就已经加载了它的Class Class<Integer> aClass2 = Integer.TYPE; // 4、对象名.getClass() String str = "Hello, World"; Class<? extends String> aClass3 = str.getClass(); // 5、Class类.getSuperClass() —— 获得父类的 Class 对象 Class<?> aClass4 = aClass3.getSuperclass(); System.out.println(aClass0.getName()); System.out.println(aClass1.getName()); System.out.println(aClass2.getName()); System.out.println(aClass3.getName()); System.out.println(aClass4.getName()); } }
3. Obtaining class information
In order to test the reflection mechanism of Java, I created a new pair of parent and child classes. It covers four encapsulation properties to test the acquisition of multiple types of information as much as possible:
Vehicle.java
vpublic class Vehicle { private String color; protected Integer seat; int year; public Date createdOn; private String getColor() { return color; } protected Integer getSeat() { return seat; } int getYear() { return year; } public Date getCreatedOn() { return createdOn; } }
Car.java
public class Car extends Vehicle { private String brand; protected Integer a; int b; public Date updatedOn; public Car(){} private Car(String brand, Integer a, int b, Date updatedOn) { this.brand = brand; this.a = a; this.b = b; this.updatedOn = updatedOn; } private String getBrand() { return brand; } protected Integer getA() { return a; } int getB() { return b; } public Date getUpdatedOn() { return updatedOn; } }
1. Obtaining methods
Class classes mainly obtain methods in the following two ways:
Method[] getMethods() returns all accessible public methods of the class or interface (Including inherited public methods).
Method[] getDeclaredMethods() Returns all methods of this class or interface (excluding inherited methods).
public class TestMethod { public static void main(String[] args) { Class<Car> carClass = Car.class; Method[] methods = carClass.getMethods(); Method[] declaredMethods = carClass.getDeclaredMethods(); for (Method method : methods) { //for (Method method : declaredMethods) { System.out.println("方法名:" + method.getName()); System.out.println("该方法所在的类或接口:" + method.getDeclaringClass()); System.out.println("该方法的参数列表:" + method.getParameterTypes()); System.out.println("该方法的异常列表:" + method.getExceptionTypes()); System.out.println("该方法的返回值类型:" + method.getReturnType()); } } }
2. Obtain attributes
Class class mainly obtains attributes through the following two methods:
Field[] getFields(): storage All accessible public properties of this class or interface (including inherited public properties).
Field[] getDeclaredFields(): Stores all properties of the class or interface (excluding inherited properties).
public class TestField { public static void main(String[] args) { Class<Car> carClass = Car.class; Field[] fields = carClass.getFields(); Field[] declaredFields = carClass.getDeclaredFields(); //for (Field field : fields) { for (Field field : declaredFields) { System.out.println("属性名称是:" + field.getName()); System.out.println("该属性所在的类或接口是:" + field.getDeclaringClass()); System.out.println("该属性的类型是:" + field.getType()); // field.getModifiers() 以整数形式返回由此 Field 对象表示的属性的 Java 访问权限修饰符 System.out.println("该属性的修饰符是:" + Modifier.toString(field.getModifiers())); } } }
3. Obtain the constructor
The Class class mainly obtains the constructor method in the following two ways:
Constructor>[ ] getConstructors(): Returns all the public constructors of the class or interface
Constructor>[] getDeclaredConstructors(): Returns all the constructors of the class or interface
public class TestConstructor { public static void main(String[] args) throws NoSuchMethodException { Class<Car> carClass = Car.class; Constructor<?>[] constructors = carClass.getConstructors(); Constructor<?>[] declaredConstructors = carClass.getDeclaredConstructors(); Constructor<Car> carConstructor = carClass.getDeclaredConstructor(String.class, Integer.class, Integer.TYPE, Date.class); //for (Constructor constructor : declaredConstructors) { for (Constructor constructor : constructors) { System.out.println("该构造器的名称是:" + constructor.getName()); System.out.println("该构造器所在的类或接口是:" + constructor.getDeclaringClass()); //返回构造方法的参数类型 constructor.getParameterTypes(); } } }
four , Dynamic call
So far, we have obtained the detailed information of the corresponding class attributes, methods and constructors through the methods of the Class class. Next we will use this information to dynamically create objects, modify properties and dynamically call methods.
public class Test { public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class<Car> carClass = Car.class; // 1、实例化对象 // 调用 Class 类的newInstance();要求对应类必须有无参构造函数,相当于 Car car = new Car() Car car = carClass.newInstance(); // 调用构造器的newInstance(Object ... initargs); Constructor<Car> declaredConstructor = carClass.getDeclaredConstructor(String.class, Integer.class, Integer.TYPE, Date.class); // 取消访问权限控制,即使是 private 权限也可以访问 declaredConstructor.setAccessible(true); Car car1 = declaredConstructor.newInstance("brand", 21, 21, new Date()); System.out.println(car1.getUpdatedOn()); // 2、修改属性 Field brand = carClass.getDeclaredField("brand"); brand.setAccessible(true); System.out.println("取消访问权限控制后的值:" + brand.get(car1)); brand.set(car1, "dnarb"); System.out.println("修改属性后的值是:" + brand.get(car1)); // 3、调用方法 Method getBrand = carClass.getDeclaredMethod("getBrand"); getBrand.setAccessible(true); System.out.println("调用反射方法得到的值是:" + getBrand.invoke(car1)); } }
The above is the detailed content of What is Java reflection? Detailed introduction to Java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Java is mainly used to build desktop applications, mobile applications, enterprise-level solutions and big data processing. 1. Enterprise-level applications: Support complex applications such as banking systems through JavaEE. 2. Web development: Use Spring and Hibernate to simplify development, and SpringBoot quickly builds microservices. 3. Mobile applications: Still one of the main languages for Android development. 4. Big data processing: Hadoop and Spark process massive data based on Java. 5. Game development: suitable for small and medium-sized game development, such as Minecraft.

How to set Java development tools to Chinese interface? It can be implemented through the following steps: Eclipse: Window->Preferences->General->Appearance->I18nsupport->Language->Chinese(Simplified), and then restart Eclipse. IntelliJIDEA: Help->FindAction->Enter "switchlanguage"->Select "SwitchIDELanguage&q

It usually takes 6 to 12 months to learn Java and reach work level, and it may be shortened to 3 to 6 months for those with a programming foundation. 1) Learners with zero foundation need to master the basics and commonly used libraries for 6-12 months. 2) Those with programming foundation may master it within 3-6 months. 3) After 9-18 months of employment, actual projects and internships can accelerate the process.

In Java, the new operator is used to create an object, and its processes include: 1) allocating space in heap memory, 2) initializing the object, 3) calling the constructor, and 4) returning the object reference. Understanding these steps can help optimize memory usage and improve application performance.

The syntax for defining arrays in Java is: 1. Data type [] Array name = new data type [array length]; 2. Data type Array name [] = new data type [array length]; 3. Data type [] Array name = {element list}; Array is an object, can be null, and the subscript starts from 0. When using it, you need to pay attention to potential errors such as NullPointerException and ArrayIndexOutOfBoundsException.

The new keyword is used in Java to create object instances. 1) It tells the JVM to allocate memory and call the constructor to initialize the object. 2) Use new to force new objects to create even if the content is the same. 3) The constructor allows custom initialization. 4) Frequent use of new may lead to performance problems and memory leaks. 5) It is necessary to use try-catch to handle possible exceptions. 6) Anonymous internal classes are advanced usage of new.

To solve the problem of Chinese garbled in Java, you can use the following steps: 1. Set the correct character encoding, such as UTF-8 or GBK, to ensure that the file, database and network communication use the same encoding. 2. Use Java's character encoding conversion class to perform necessary encoding conversion. 3. Verify whether the encoding is correct through debugging tools and logs to ensure that the Chinese display is normal in different environments.

Exceptions in Java are divided into checked exceptions and non-checked exceptions. Check-type exceptions must be handled explicitly, otherwise the compiler will report an error, which is often used to recover errors, such as a file not found; non-checked exceptions do not need to be handled explicitly, and are often used for programming errors, such as a null pointer exception.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
