In Java's reflection mechanism,getDeclaredMethods()
It is a very important method, which allows us to obtain all methods declared in the class (including methods with public, private, protected, and default access rights). Through this method, we can dynamically analyze and manipulate the behavior of classes, which is very useful in scenarios such as framework development, testing tools, and dynamic proxying. This article will discuss in depthgetDeclaredMethods()
How to use, principles and precautions to help you better understand and apply it.
1. What is getDeclaredMethods()?
getDeclaredMethods()
yesA method in the class that returns all methods declared in the current class (excluding inherited methods). These methods include:
- Public method (
public
) - Private method (
private
) - Protection method (
protected
) - Methods for default access permissions (package private)
It should be noted thatgetDeclaredMethods()
Methods inherited from the parent class or interface are not returned.
2. How to use getDeclaredMethods()
Here is a simple example showing how to use itgetDeclaredMethods()
Get all methods declared in the class:
import ; public class MyClass { public void publicMethod() {} private void privateMethod() {} protected void protectedMethod() {} void defaultMethod() {} public static void main(String[] args) { Class<?> clazz = ; Method[] methods = (); for (Method method : methods) { ("Method Name: " + ()); ("Modifier: " + ()); ("Return Type: " + ()); ("Parameters: " + ()); ("-----"); } } }
Output result:
Method Name: publicMethod
Modifier: 1
Return Type: void
Parameters: 0
-----
Method Name: privateMethod
Modifier: 2
Return Type: void
Parameters: 0
-----
Method Name: protectedMethod
Modifier: 4
Return Type: void
Parameters: 0
-----
Method Name: defaultMethod
Modifier: 0
Return Type: void
Parameters: 0
-----
From the output, you can see thatgetDeclaredMethods()
All methods declared in the class were successfully obtained, including private methods and protected methods.
3. Analysis of the principle of getDeclaredMethods()
getDeclaredMethods()
The implementation depends on Java's reflection mechanism. Its core principle is as follows:
Class loading and metadata
When a Java Virtual Machine (JVM) loads a class, it generates one for each class.Class
Object, which contains the metadata of the class (such as methods, fields, constructors, etc.).getDeclaredMethods()
Accessing these metadata to get the methods declared in the class.
Storage of method information
Method information (such as method name, parameter type, return type, access modifier, etc.) is stored inMethod
in object.getDeclaredMethods()
Returns is aMethod
Array, eachMethod
The object corresponds to a method.
Checking of access permissions
By default,getDeclaredMethods()
All declared methods can be obtained, including private methods. But if the security manager is enabled (SecurityManager
), then it may be thrownSecurityException
。
4. Difference from getMethods()
getMethods()
andgetDeclaredMethods()
They are two commonly used methods in Java reflection. The differences are as follows:
getMethods()
Returns all public methods in the current class and its parent class and interface (public
)。
getDeclaredMethods()
Returns only all methods declared in the current class (including methods with private, protected, default access permissions), excluding inherited methods.
Example:
class Parent { public void parentMethod() {} } class Child extends Parent { public void childMethod() {} private void privateMethod() {} } public class Main { public static void main(String[] args) { Class<?> clazz = ; ("getMethods():"); for (Method method : ()) { (()); } ("====================================="); ("getDeclaredMethods():"); for (Method method : ()) { (()); } } }
Output result:
getMethods():
childMethod
parentMethod
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
=====================================
getDeclaredMethods():
childMethod
privateMethod
5. Practical application scenarios
getDeclaredMethods()
Very useful in the following scenarios:
- Dynamic Agent: Obtain the target class method through reflection and generate the proxy class dynamically.
- Unit Testing: When testing private methods, these methods can be called through reflection.
- Framework Development: For example, in the Spring framework, parse the annotations through reflection and execute the corresponding logic.
- Code analysis tools: Analyze the method structure of the class, generate documents or perform code checks.
6. Precautions and FAQs
- Performance issues
Reflection operations are slower than calling methods directly, so they should be used with caution in performance-sensitive scenarios.
- Access private methods
If you need to call a private method, you need to call it first(true)
To bypass access permission checking.
- Security Manager
If Security Manager is enabled, access to certain methods may be restricted, resulting inSecurityException
。
- The missing inheritance method
getDeclaredMethods()
The inherited method will not be returned. If you need to obtain the parent method, you can use it.getMethods()
。
7. Summary
getDeclaredMethods()
It is a powerful tool in the Java reflection mechanism, which allows us to dynamically obtain all methods declared in a class. In actual development, the rational use of reflection can greatly improve the flexibility and scalability of the code, but it should also pay attention to its performance overhead and security issues.
This is the article about getDeclaredMethods() method in Java: The full guide to use and principles. This is all about this article. For more related java getDeclaredMethods() method content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!