Home > Java > javaTutorial > How to get reflection method in Java?

How to get reflection method in Java?

王林
Release: 2023-04-23 20:16:05
forward
2052 people have browsed it

1. Get the method to be reflected

When getting the reflection method, there are two methods, getMethod and getDeclaredMethod.

class Class {
 @CallerSensitive
 public Method getMethod(String name, Class<?>... parameterTypes)
 throws NoSuchMethodException, SecurityException {
 Objects.requireNonNull(name);
 SecurityManager sm = System.getSecurityManager();
 if (sm != null) {
 // 1. 检查方法权限
 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
 }
 // 2. 获取方法
 Method method = getMethod0(name, parameterTypes);
 if (method == null) {
 throw new NoSuchMethodException(methodToString(name, parameterTypes));
 }
 // 3. 返回方法的拷贝
 return getReflectionFactory().copyMethod(method);
 }
 @CallerSensitive
 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
 throws NoSuchMethodException, SecurityException {
 Objects.requireNonNull(name);
 SecurityManager sm = System.getSecurityManager();
 if (sm != null) {
 // 1. 检查方法是权限
 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
 }
 // 2. 获取方法
 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
 if (method == null) {
 throw new NoSuchMethodException(methodToString(name, parameterTypes));
 }
 // 3. 返回方法的拷贝
 return getReflectionFactory().copyMethod(method);
 }
}
Copy after login

2. In Java5, a for-each loop is provided, which simplifies looping of arrays and collections. Fore-each loops allow you to iterate over an array without retaining the index in a traditional for loop or calling the hasNext method and next method in a while loop when using an iterator to iterate through the collection.

double[] values = ...;
for(double value : values) {
    // TODO: 处理value
}
 
List<Double> valueList = ...;
for(Double value : valueList) {
    // TODO: 处理value
}
Copy after login

3. Get the name of the current method

<span style=
"font-family:Arial;font-size:14px;"
>String methodName = Thread.currentThread().getStackTrace()[
1
].getMethodName(); </span>
Copy after login

The above is the detailed content of How to get reflection method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template