search
HomeJavajavaTutorialWhat reflection is java?

What reflection is java?

Nov 18, 2019 pm 02:14 PM
javareflection

What reflection is java?

#What reflection is java?

Reflection is one of the features of Java and is a mechanism for indirectly operating target objects.

The JAVA reflection mechanism is that in the running state, for any entity class, all properties and methods of this class can be known; for any object, any method and property of it can be called; this kind of dynamic The function of obtaining information and dynamically calling object methods is called the reflection mechanism of the Java language.

Why is reflection needed in Java? What problem does reflection solve?

In one sentence, reflection can give jvm the ability to compile dynamically. Otherwise, the metadata information of the class can only be achieved by static compilation, such as hot loading, Tomcat's Classloader, etc. cannot support

There are two types of compilation in Java:

● Static compilation: The type is determined at compile time, and the bound object is passed.

● Dynamic compilation: determine the type and bind the object at runtime. Dynamic compilation maximizes the flexibility of Java, embodies polymorphic applications, and can reduce coupling between classes.

Java Reflection is a key property of Java being considered a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain the internal information of any class with a known name through the Reflection APIs at runtime, including its modifiers (such as public, static, etc.), superclass (such as Object), implemented interfaces (such as Cloneable), and All information about fields and methods, and can change the contents of fields or invoke methods at runtime.

Reflection can load, detect, and use classes that are completely unknown during compilation at runtime. That is, a Java program can load a class whose name is known only at runtime, obtain its complete structure, and generate its object entity, or set values ​​for its fields, or invoke its methods.

Reflection allows static languages ​​to inspect and modify the structure and behavior of the program at runtime.
In static languages, when using a variable, you must know its type. In Java, the type information of variables is saved in the class file during compilation, so that it can be accurate at runtime; in other words, the behavior of the program at runtime is fixed. If you want to change it at runtime, you need reflection.

The classes that implement the Java reflection mechanism are all located in the java.lang.reflect package:

1. Class class: represents a class

2. Field class: represents a class Member variables (properties of the class)

3. Method class: represents the method of the class

4. Constructor class: represents the construction method of the class

5. Array class: provides To dynamically create arrays and access static methods of array elements

Use

What reflection is java?

1. Three ways to obtain Class objects

1.1 Object ——> getClass();
1.2 Any data type (including basic data types) There is a "static" class attribute
1.3 Through the static method of the Class class: forName (String className) (commonly used)

/**
 * 获取Class对象的三种方式
 * 1 Object ——> getClass();
 * 2 任何数据类型(包括基本数据类型)都有一个“静态”的class属性
 * 3 通过Class类的静态方法:forName(String  className)(常用)
 *
 */
public class Fanshe {
	public static void main(String[] args) {
		//第一种方式获取Class对象  
		Student stu1 = new Student();//这一new 产生一个Student对象,一个Class对象。
		Class stuClass = stu1.getClass();//获取Class对象
		System.out.println(stuClass.getName());
		
		//第二种方式获取Class对象
		Class stuClass2 = Student.class;
		System.out.println(stuClass == stuClass2);
//判断第一种方式获取的Class对象和第二种方式获取的是否是同一个
		
		//第三种方式获取Class对象
		try {
			Class stuClass3 = Class.forName("fanshe.Student");
//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名
			System.out.println(stuClass3 == stuClass2);
//判断三种方式是否获取的是同一个Class对象
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
 
		System.out.println("*****************获取公有、无参的构造方法*************");
		Constructor con = clazz.getConstructor(null);
		//1>、因为是无参的构造方法所以类型是一个null,不写也可以:这里需要的是一个参数的类型,切记是类型
		//2>、返回的是描述这个无参构造函数的类对象。
 
 
		System.out.println("*************获取公有字段**并调用*****************");
		Field f = stuClass.getField("name");
        System.out.println(f);
		
 
		System.out.println("***************获取私有的show4()方法******************");
		m = stuClass.getDeclaredMethod("show4", int.class);
		System.out.println(m);
		m.setAccessible(true);//解除私有限定
		Object result = m.invoke(obj, 20);//需要两个参数,一个是要调用的对象(获取有反射),一个是实参
		System.out.println("返回值:" + result);
 
	}
}

The above is the detailed content of What reflection is java?. 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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools