今天才知道Java的反射這么強(qiáng)大展鸡,可以完全不知道方法名迹卢、參數(shù)拗小、返回值就能進(jìn)行方法調(diào)用,而且還能拿到方法的返回值,遍歷返回值中的集合等努隙。
自定義注解:
package Reflect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @ClassName TestMethod
* @description:
* @author: isquz
* @time: 2020/10/20 22:08
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestMethod {
String params();
}
方法使用注解:
package Reflect;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName MethodAnnotation
* @description:
* @author: isquz
* @time: 2020/10/20 22:11
*/
public class MethodAnnotation {
public List<String> returnParamList(){
List<String> list = new ArrayList<>();
list.add("String1");
list.add("String2");
list.add("String3");
return list;
}
@TestMethod(params = "returnParamList")
public void testMethodWithAnnotation(String s){
System.out.println("獲取注解傳遞的參數(shù)集合" + s);
}
}
反射調(diào)用注解:
package Reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
/**
* @ClassName TestMethodAnnotation
* @description:
* @author: isquz
* @time: 2020/10/20 22:07
*/
public class TestMethodAnnotation {
public static void main(String[] args) {
Class<?> cls = MethodAnnotation.class;
Method[] methods = cls.getDeclaredMethods();
try {
for(Method method:methods){
TestMethod methodInfo = method.getAnnotation(TestMethod.class);
if(methodInfo != null){
System.out.println("添加注解的方法名:" + method.getName());
String param = methodInfo.params();
Class<?>[] methodParamType = method.getParameterTypes();
String variable = methodParamType[0].getSimpleName();
System.out.println("測(cè)試方法所需參數(shù)類型:" + variable);
System.out.println("注解中參數(shù)來(lái)源方法:" + param);
Method paramMethod = cls.getDeclaredMethod(param);
Method testMethod = cls.getDeclaredMethod(method.getName(), variable.getClass());
Iterable<?> paramList = (Iterable<?>) paramMethod.invoke(cls.newInstance());
Iterator<?> iterator = paramList.iterator();
while (iterator.hasNext()){
testMethod.invoke(cls.newInstance(), iterator.next());
}
}
}
}catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}