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); } }
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 }
3. Get the name of the current method
<span style= "font-family:Arial;font-size:14px;" >String methodName = Thread.currentThread().getStackTrace()[ 1 ].getMethodName(); </span>
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!