PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Java中如何获取反射方法?

王林
王林 转载
2023-04-23 20:16:05 1520浏览

1、获取要反射的方法

获取反射方法时,有两个方法,getMethod 和 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);
 }
}

2、在Java5中,提供了for-each循环,从而简化了对数组和集合的循环。Fore-each循环允许您遍历数组而不需要保留传统for循环中的索引,也不需要在使用迭代器时调用while循环中的hasNext方法和next方法来遍历集合。

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

3、得到当前方法的名字

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

以上就是Java中如何获取反射方法?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除