原作者: 尚硅谷-佟刚
@Test
public void testReflectionAndAnnotation() throws Exception{
String className="com.atweihai.reflection.Student";
int val=20;
Class clazz=Class.forName(className);
Object obj=clazz.newInstance();
Method method=getMethod(clazz, "setAge", Integer.class);
AgeValidator ageValidator=method.getAnnotation(AgeValidator.class);
if(ageValidator!=null){
if(val<ageValidator.min()||val>ageValidator.max()){
throw new RuntimeException("年龄非法!");
}
method.invoke(obj, val);
System.out.println(((Student)obj).getAge());
}
}
//获取方法
public Method getMethod(Class clazz,String methodName,Class ... parameterTypes){
Method method=null;
//循环向上转型
for(;clazz!=Object.class;clazz=clazz.getSuperclass()){
try {
method=clazz.getDeclaredMethod(methodName, parameterTypes);
return method;
} catch (Exception e) {}
}
return method;
}