search
HomeJavajavaTutorialBasic principles and calling methods of Java reflection

Basic principles and calling methods of Java reflection

Dec 23, 2023 am 09:01 AM
reflectionprinciplemethod invocation

Basic principles and calling methods of Java reflection

Basic principles and calling methods of Java reflection

Foreword:
Java reflection is an important feature in the Java language, which allows the program to dynamically Obtain class information and operate class members. Through reflection, we can dynamically create objects, call methods, get/set properties, etc. at runtime, which greatly improves the flexibility and scalability of the program. This article will introduce the basic principles of Java reflection and give specific code examples.

1. Basic principles of reflection
The implementation of Java reflection is based on the Class class, which is the core class of Java reflection. Each Java class will generate a corresponding Class object after compilation. Class information can be obtained through the Class object, and class operations can be performed through the class information.

Java reflection mainly has the following core classes and interfaces:

  1. Class class: represents the type of class, which is the entry point of Java reflection.
  2. Field class: represents the member variables of the class.
  3. Method class: represents the member method of the class.
  4. Constructor class: Represents the constructor method of the class.

The basic principle of Java reflection is as follows: first, obtain the corresponding Class object through the fully qualified name of the class or the getClass() method of the object; then, through some methods of the Class class, such as getFields() , getMethods(), etc., to obtain Field, Method, Constructor and other objects; finally, perform specific operations through these objects, such as getting/setting attribute values, calling methods, creating objects, etc.

2. Reflection calling method
2.1 Obtain Class object
The corresponding Class object can be obtained through the fully qualified name of the class or the getClass() method of the object.

The sample code is as follows:

// 通过类的全限定名获取Class对象
Class<?> clazz1 = Class.forName("com.example.User");

// 通过对象的getClass()方法获取Class对象
User user = new User();
Class<?> clazz2 = user.getClass();

2.2 Obtaining the attribute value
The attribute value of the object can be obtained through the get() method of the Field class.

The sample code is as follows:

// 获取public属性值
Field field = clazz.getDeclaredField("name");
String name = (String) field.get(user);

// 获取private属性值
Field privateField = clazz.getDeclaredField("age");
privateField.setAccessible(true); // 设置private属性的访问权限
int age = (int) privateField.get(user);

2.3 Setting the attribute value
The attribute value of the object can be set through the set() method of the Field class.

The sample code is as follows:

// 设置public属性值
Field field = clazz.getDeclaredField("name");
field.set(user, "Tom");

// 设置private属性值
Field privateField = clazz.getDeclaredField("age");
privateField.setAccessible(true); // 设置private属性的访问权限
privateField.set(user, 20);

2.4 Calling the method
The method of the object can be called through the invoke() method of the Method class.

The sample code is as follows:

// 调用无参方法
Method method1 = clazz.getDeclaredMethod("sayHello");
method1.invoke(user);

// 调用带参方法
Method method2 = clazz.getDeclaredMethod("sayHi", String.class);
method2.invoke(user, "Jack");

2.5 Creating objects
Objects can be created through the newInstance() method of the Constructor class.

The sample code is as follows:

Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);
User newUser = (User) constructor.newInstance("Lucy", 25);

Summary:
Java reflection is a powerful feature in the Java language, which can dynamically obtain class information and operate class members at runtime . The basic principle of reflection is to obtain class information through the Class class and perform specific operations through Field, Method, Constructor and other objects. In actual applications, we can use the reflection mechanism to realize various dynamic requirements and improve the flexibility and scalability of the program.

The above is the detailed content of Basic principles and calling methods of Java reflection. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software