In Java reflection mechanism,getDeclaredFields()
It is a very important method, which allows developers to dynamically obtain all fields of a class (including private fields). Through reflection, we can obtain internal information of the class and operate its members at runtime, which is very useful in some scenarios, such as framework development, testing tools, dynamic proxying, etc. This article will discuss in depthgetDeclaredFields()
How to use, how to work, and best practices.
1. Basic introduction to getDeclaredFields()
getDeclaredFields()
yesA method in the class that gets all fields of the class (
Field
Object array). andgetFields()
Different methods,getDeclaredFields()
All fields of the class can be accessed, includingprivate
、protected
and default access fields, andgetFields()
Accessible onlypublic
Field.
Method signature
public Field[] getDeclaredFields() throws SecurityException
-
Return value: Return one
Field
Array, representing all fields of the class. - abnormal:
SecurityException
: If a security manager exists and the fields are not allowed.
2. How to use getDeclaredFields()
2.1 Get all fields of the class
passgetDeclaredFields()
All fields of the class can be retrieved, including private fields. ReturnedField
The array contains all field information of the class.
Example:
import ; public class Main { private String name = "Java"; public int age = 25; public static void main(String[] args) { try { // Get the Class object of the Main class Class<?> clazz = ; // Get all fields Field[] fields = (); // traverse the fields and print information for (Field field : fields) { ("Field Name: " + ()); ("Field Type: " + ().getName()); ("Field Modifier: " + ()); ("-----"); } } catch (Exception e) { (); } } }
Output:
Field name: name
Field Type:
Field modifier: 2
-----
Field name: age
Field type: int
Field modifier: 1
-----
2.2 Accessing the value of a private field
passgetDeclaredFields()
After obtaining the field, you can use itField
Classicget()
Method accesses the value of the field. If the field is private, it needs to be called firstsetAccessible(true)
To bypass access permission checking.
Example:
import ; public class Main { private String name = "Java"; public int age = 25; public static void main(String[] args) { try { Class<?> clazz = ; Field[] fields = (); Main obj = new Main(); for (Field field : fields) { (true); // Set accessibility ("Field Name: " + ()); ("Field Value: " + (obj)); ("-----"); } } catch (Exception e) { (); } } }
Output:
Field name: name
Field value: Java
-----
Field name: age
Field value: 25
-----
3. How does getDeclaredFields() work
3.1 The core of the reflection mechanism
getDeclaredFields()
is part of the Java reflection mechanism. The reflection mechanism allows the program to dynamically obtain the information of the class (such as fields, methods, constructors, etc.) at runtime and operate these members. The core class of reflection isClass
, it represents the type information of a class or interface.
3.2 Field acquisition process
When calledgetDeclaredFields()
When the JVM gets all fields information from the class's metadata and returns aField
Array. This array contains all the fields of the class, regardless of their access permissions.
3.3 Bypass of access permissions
By default, the JVM checks the fields' access permissions. If the field is private, direct access will be thrownIllegalAccessException
. By calling(true)
, you can bypass access permission checks to access private fields.
4. Use scenarios of getDeclaredFields()
4.1 Framework Development
In framework development, it is often necessary to dynamically access and manipulate fields of classes. For example, Spring framework injects dependencies through reflection.
4.2 Test tools
In unit testing, it is sometimes necessary to access the private fields of the class to verify its state. passgetDeclaredFields()
, this can be achieved conveniently.
4.3 Dynamic Agent
In a dynamic proxy, it may be necessary to obtain the field information of the target object for use in the proxy logic.
4.4 Serialization and deserialization
During custom serialization and deserialization, you may need to obtain all field information of the class.
5. Best practices for getDeclaredFields()
5.1 Use reflection with caution
Although strong reflections are, they will bring performance overhead and destroy packaging. Therefore, excessive use of reflection in performance-sensitive code should be avoided.
5.2 Handling exceptions
getDeclaredFields()
Possible to throwSecurityException
, therefore these exceptions need to be properly handled.
Example:
try { Field[] fields = (); } catch (SecurityException e) { ("Safety exception: " + ()); }
5.3 Cache Field Array
If you need to access the field of the class multiple times, you canField
Cache arrays to avoid repeated callsgetDeclaredFields()
。
Example:
private static Field[] cachedFields; static { try { cachedFields = (); for (Field field : cachedFields) { (true); } } catch (Exception e) { (); } }
5.4 Notes on using setAccessible()
setAccessible(true)
Access permission checking will be bypassed, so you should use it with caution to avoid damaging encapsulation.
6. Summary
getDeclaredFields()
It is an important method in the Java reflection mechanism, which allows developers to dynamically obtain all fields of a class (including private fields). Through reflection, we can get internal information of a class at runtime and manipulate its members, which is very useful in some scenarios.
However, the reflection mechanism also brings performance overhead and packaging problems, so it should be used with caution in actual development. Follow best practices such as handling exceptions, cacheField
Arrays, etc., can help us make better use of themgetDeclaredFields()
Powerful features.
I hope this article can help you understand in depthgetDeclaredFields()
how to use and working principle, so as to flexibly use the reflection mechanism in appropriate scenarios.
This is the article about getDeclaredFields() in Java: Detailed explanation of the usage and principles. For more related content on Java getDeclaredFields, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!