Home Java javaTutorial Basic principles and calling methods of Java reflection

Basic principles and calling methods of Java reflection

Dec 23, 2023 am 09:01 AM
reflection principle method 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();
Copy after login

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);
Copy after login

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);
Copy after login

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");
Copy after login

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);
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Reflection principles and application scenarios in Go language Reflection principles and application scenarios in Go language Jun 01, 2023 am 08:30 AM

The Go language comes with a reflection mechanism, which is one of its biggest features. Reflection provides the Go language with a way to check variables and call methods at runtime, which allows us to understand and manipulate data in the program in a common, unified way without caring about the type of specific data. This is programming A common problem in language. In this article, we will delve into the reflection principles and application scenarios in the Go language. What is reflection? In the computer field, reflection refers to dynamically detecting the type of data or operating on data at runtime.

Basic principles and calling methods of Java reflection Basic principles and calling methods of Java reflection Dec 23, 2023 am 09:01 AM

Basic principles of Java reflection and calling methods Preface: Java reflection is an important feature of the Java language, which allows programs to dynamically obtain class information and operate class members at runtime. 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. The basic principles of reflection. The implementation of Java reflection is based on the Class class. Class

How to use reflection and metadata to handle code generation and extension in C# and solutions How to use reflection and metadata to handle code generation and extension in C# and solutions Oct 09, 2023 am 10:48 AM

How to use reflection and metadata to handle code generation and extension and solutions in C#, specific code examples are required Title: Methods and solutions for using reflection and metadata to generate and extend code in C# Introduction: Reflection and metadata in C# development It is a very powerful tool that can help us achieve the function of dynamically generating and expanding code. This article describes how to use reflection and metadata to handle code generation and extension, and provides specific code examples. 1. Use reflection to generate code. Through reflection, we can dynamically load and check at runtime.

Detailed explanation of the comprehensive application of closures, generators and reflection technology in PHP Detailed explanation of the comprehensive application of closures, generators and reflection technology in PHP Sep 13, 2023 pm 12:13 PM

Detailed explanation of the comprehensive application of closures, generators and reflection technologies in PHP Introduction: As the complexity of web applications continues to increase, developers need more advanced and flexible technologies to deal with these challenges. PHP is a popular server-side scripting language that offers many powerful features, including closures, generators, and reflection. This article will introduce the comprehensive application of these technologies in detail and provide specific code examples. 1. Closure: Closure refers to a function defined inside a function and can access its outside

What are the principles and usage scenarios of decorators and context managers in Python? What are the principles and usage scenarios of decorators and context managers in Python? Oct 18, 2023 am 10:41 AM

Decorators and context managers in Python are two very useful features that can help us better organize and manage code and improve code reusability. This article will introduce the principles and usage scenarios of decorators and context managers respectively, and give specific code examples. 1. Principles and usage scenarios of decorators: Decorators are a way to add additional functions to a function without changing the definition of the original function. It is actually a function that accepts the decorated function as input and returns the wrapped function. decorate

Demystifying Java Reflection: Exploring the Deep Mysteries of How It Works Demystifying Java Reflection: Exploring the Deep Mysteries of How It Works Dec 23, 2023 pm 12:49 PM

Decrypting Java Reflection: To explore the principles behind it, specific code examples are required. Introduction: In Java programming, reflection (Reflection) is a powerful and flexible mechanism that allows us to dynamically inspect classes, interfaces, fields and methods at runtime. , they can be called and manipulated even without knowing the concrete class. This article will delve into the principles behind Java reflection and provide specific code examples to help readers better understand and apply reflection. What is reflection? In short, reflection is a method of obtaining and manipulating

How to use Go language for code reflection practice How to use Go language for code reflection practice Aug 01, 2023 pm 10:58 PM

How to use Go language for code reflection practice introduction: In Go language, reflection is a powerful mechanism that allows us to dynamically check type information and manipulate objects while the program is running. Through reflection, we can call methods, access fields, create instances, etc. without knowing the specific type. This article will introduce how to use the reflection mechanism of Go language for code practice and give corresponding code examples. Reflection Basics Reflection refers to the ability to inspect variables, categories, methods, and interfaces when a program is running. In Go language, reflection is

Three ways to learn Java reflection skills Three ways to learn Java reflection skills Jan 03, 2024 pm 02:00 PM

Learn more about the three techniques of Java reflection Introduction: Java reflection is a powerful programming technique that can dynamically obtain class-related information and operate class members at runtime. This article will introduce three advanced techniques of Java reflection and give specific code examples. Obtaining complete information of a class Through Java reflection, we can obtain complete information of a class, including class name, parent class, implemented interfaces, methods, fields, etc. Here is a sample code to get complete information about a class: importjava.lang

See all articles