java通过反射,动态调用指定注解的方法
@SpringBootTest
@RunWith(SpringRunner.class)
public class AnnoTest {@Autowiredprivate ApplicationContext applicationContext;@Testpublic void test(){// 获取有指定注解的BeanMap<String, Object> annotationMap = applicationContext.getBeansWithAnnotation(CacheConfig.class);for (Map.Entry<String, Object> map : annotationMap.entrySet()){String key = map.getKey();Object bean = map.getValue();
// 通过obj.getClass().getSuperclass()来获取代理类的真实类Class<?> clazz = bean.getClass().getSuperclass();Method[] declaredMethods = clazz.getDeclaredMethods();for (Method method : declaredMethods) {// 找到有对应的注解的方法if (method.isAnnotationPresent(Cacheable.class)) {// 判断方法名是否是指定的String name = method.getName();if("getUser".equals(name)){System.out.println("找到目标方法");try {Object invoke = method.invoke(bean, 523L);System.out.println(invoke);} catch (Exception e) {e.printStackTrace();}}}}}}}
需要注意的是:由于使用了 CGLIB,所以需要使用 “bean.getClass().getSuperclass()” 才可以获取到真实的类。如果没有使用CGLIB,直接使用 “bean.getClass()”即可获取到真实的类。