Reflections index metadata by scanning the classpath, allowing these metadata to be queried at runtime, and can also save and collect metadata information for multiple modules in the project.
Use Reflections to quickly scan the customized Controller and RequestMapping annotations under the specified package. First scan the classes annotated with @Controller, then obtain the methods annotated with @RequestMapping under these classes, and then use Java The reflection invoke method calls the method annotated with RequestMapping and outputs the information on the annotation.
Maven project import
<dependency> <groupid>org.reflections</groupid> <artifactid>reflections</artifactid> <version>0.9.10</version> </dependency>
There are two annotations customized under the annotation package.
Controller.java:
package annotationTest.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE)// 注解会在class字节码文件中存在,在运行时可以通过反射获取到 @Retention(RetentionPolicy.RUNTIME)//定义注解的作用目标**作用范围字段、枚举的常量/方法 @Documented//说明该注解将被包含在javadoc中 public @interface Controller { String value() default ""; }
RequestMapping.java
package annotationTest.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface RequestMapping { String value() default ""; /** * 是否为序列号 * * @return */ boolean id() default false; /** * 字段名称 * * @return */ String name() default ""; /** * 字段描述 * * @return */ String description() default ""; }
An object storing the RequestMapping annotation method is defined under the model package
ExecutorBean.java
package annotationTest.model; import java.lang.reflect.Method; public class ExecutorBean { private Object object; private Method method; public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; } }
The service package defines several classes, two of which use custom Controller annotations
SunService. java
package annotationTest.service; import annotationTest.annotation.Controller; import annotationTest.annotation.RequestMapping; @Controller public class SunService { @RequestMapping(id = true, name = "test1", description = "sun测试1", value = "/test1") public void test1() { System.out.println("SunService->test1()"); } @RequestMapping(id = true, name = "test2", description = "sun测试2", value = "/test2") public void test2() { System.out.println("SunService->test2()"); } }
MoonService.java
package annotationTest.service; import annotationTest.annotation.Controller; import annotationTest.annotation.RequestMapping; @Controller public class MoonService { @RequestMapping(id = true, name = "moon测试3", description = "/test3", value = "/test3") public void test3() { System.out.println("MoonService->test3()"); } @RequestMapping(id = true, name = "moon测试4", description = "/test4", value = "/test4") public void test4() { System.out.println("MoonService->test4()"); } }
Stars.java
package annotationTest.service; import annotationTest.annotation.RequestMapping; public class Stars { @RequestMapping(id = true, name = "test1", description = "stars测试1", value = "/test1") public void test1() { System.out.println("Stars->test1()"); } }
The util package defines a tool class to scan the package to obtain custom annotations. Classes and methods
AnnoManageUtil.java
package annotationTest.util; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Set; import annotationTest.annotation.Controller; import annotationTest.annotation.RequestMapping; import annotationTest.model.ExecutorBean; import org.reflections.Reflections; public final class AnnoManageUtil { /** * 获取指定文件下面的RequestMapping方法保存在mapp中 * * @param packageName * @return */ public static Map<string> getRequestMappingMethod(String packageName) { Reflections reflections = new Reflections(packageName); Set<class>> classesList = reflections.getTypesAnnotatedWith(Controller.class); // 存放url和ExecutorBean的对应关系 Map<string> mapp = new HashMap<string>(); for (Class classes : classesList) { //得到该类下面的所有方法 Method[] methods = classes.getDeclaredMethods(); for (Method method : methods) { //得到该类下面的RequestMapping注解 RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (null != requestMapping) { ExecutorBean executorBean = new ExecutorBean(); try { executorBean.setObject(classes.newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } executorBean.setMethod(method); mapp.put(requestMapping.value(), executorBean); } } } return mapp; } }</string></string></class></string>
The following test package is a test class
package annotationTest.test; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.List; import java.util.Map; import annotationTest.annotation.Controller; import annotationTest.annotation.RequestMapping; import annotationTest.model.ExecutorBean; import annotationTest.util.AnnoManageUtil; public class Test { public static void main(String[] args) { List<class>> classesList = null; classesList = AnnoManageUtil.getPackageController("annotationTest.service", Controller.class); Map<string> mmap = new HashMap<string>(); AnnoManageUtil.getRequestMappingMethod(classesList, mmap); ExecutorBean bean = mmap.get("/test1"); try { bean.getMethod().invoke(bean.getObject()); RequestMapping annotation = bean.getMethod().getAnnotation(RequestMapping.class); System.out.println("注解名称:" + annotation.name() + "\t注解描述:" + annotation.description()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }</string></string></class>
Run and get:
Others
-
Using Reflections, you can query the following metadata information:
Reflections relies on Google’s Guava library and Javassist library.
Get all subtypes of a certain type
Get all types/member variables marked with a certain annotation, support annotations Parameters match.
Use regular expressions to get all matching resource files
Method to get all specific signatures (including parameters, parameter annotations, return values)
After using annotations to modify classes/methods/member variables, etc., these annotations will not take effect by themselves. The developers of these annotations must provide corresponding tools to extract and process them. Annotation information (of course, only when the @Retention(RetentionPolicy.RUNTIME) modification is used when defining the annotation, the JVM will extract the annotations saved in the class file when loading the class file, and the annotation will be visible at runtime, so that we can Able to parse).
Java uses the Annotation interface to represent the annotations in front of program elements. This interface is the parent interface of all annotations.
java5 has added the AnnotatedElement interface under the java.lang.reflect package to represent program elements that can accept annotations in the program.
AnnotatedElement The implementation classes of the interface are: Class (class element), Field (member variable element of the class), Method (method element of the class), and Package (package element). Each implementation class represents a program element type that can accept annotations.
In this way, we only need to obtain instances of Class, Method, Filed and other classes that implement the AnnotatedElement interface, and call the methods in the class through the instance object (abstract in the AnnotatedElement interface method), we can get the annotation information we want.
There are three ways to obtain an instance of the Class class:
Use the object to call the getClass() method to obtain a Class instance
Use the static forName() method of the Class class to obtain the Class instance using the class name
- ##Use the .class method to obtain the Class instance, such as: class name .class
T getAnnotation(Class annotationClass)< T extends Annotation> is a generic parameter declaration, indicating that the type of A can only be the Annotation type or a subclass of Annotation. Function: Return the annotations of the specified type that exist on the program element. If the annotation of this type does not exist, return null
- Annotation[] getAnnotations()
Function: Returns all annotations that exist on this element, including annotations that are not explicitly defined on this element (inherited). (If this element has no annotation, a zero-length array is returned.)
- T getDeclaredAnnotation(Class annotationClass)
Function: This It is a new method in Java 8. This method returns annotations that directly modify the program element and specify the type (ignoring inherited annotations). If annotations of this type do not exist, return null.
- Annotation[] getDeclaredAnnotations()
Function: Return all annotations that exist directly on this element, this method will ignore inheritance annotation. (If no annotation exists directly on this element, an array with a length of zero is returned.)
- boolean isAnnotationPresent(Class extends Annotation> annotationClass)
Function: Judgment Whether there is an annotation of the specified type on the program element. If it exists, it returns true, otherwise it returns false.
<T extends Annotation> T[] getAnnotationsByTpye(Class
annotationClass)
Function: Because java8 adds a repeated annotation function, you need to use this method to obtain the modified program element and the specified type. multiple annotations.- ##
T[] getDeclaredAnnotationsByTpye(Class annotationClass) Function: Because java8 has added the repeated annotation function, you need to use this method to obtain direct modification This program element, multiple annotations of the specified type.
The above is the detailed content of Get all custom annotations under the specified package. For more information, please follow other related articles on the PHP Chinese website!

Netflix上的头像是你流媒体身份的可视化代表。用户可以超越默认的头像来展示自己的个性。继续阅读这篇文章,了解如何在Netflix应用程序中设置自定义个人资料图片。如何在Netflix中快速设置自定义头像在Netflix中,没有内置功能来设置个人资料图片。不过,您可以通过在浏览器上安装Netflix扩展来实现此目的。首先,在浏览器上安装Netflix扩展的自定义个人资料图片。你可以在Chrome商店买到它。安装扩展后,在浏览器上打开Netflix并登录您的帐户。导航至右上角的个人资料,然后单击

Win11如何自定义背景图片?在最新发布的win11系统中,里面有许多的自定义功能,但是很多小伙伴不知道应该如何使用这些功能。就有小伙伴觉得背景图片比较单调,想要自定义背景图,但是不知道如何操作自定义背景图,如果你不知道如何定义背景图片,小编下面整理了Win11自定义背景图片步骤,感兴趣的话一起往下看看把!Win11自定义背景图片步骤1、点击桌面win按钮,在弹出的菜单中点击设置,如图所示。2、进入设置菜单,点击个性化,如图所示。3、进入个性化,点击背景,如图所示。4、进入背景设置,点击浏览图片

维恩图是用来表示集合之间关系的图。要创建维恩图,我们将使用matplotlib。Matplotlib是一个在Python中常用的数据可视化库,用于创建交互式的图表和图形。它也用于制作交互式的图像和图表。Matplotlib提供了许多函数来自定义图表和图形。在本教程中,我们将举例说明三个示例来自定义Venn图。Example的中文翻译为:示例这是一个创建两个维恩图交集的简单示例;首先,我们导入了必要的库并导入了venns。然后我们将数据集创建为Python集,之后,我们使用“venn2()”函数创

CakePHP是一个强大的PHP框架,为开发人员提供了很多有用的工具和功能。其中之一是分页,它可以帮助我们将大量数据分成几页,从而简化浏览和操作。默认情况下,CakePHP提供了一些基本的分页方法,但有时你可能需要创建一些自定义的分页方法。这篇文章将向您展示如何在CakePHP中创建自定义分页。步骤1:创建自定义分页类首先,我们需要创建一个自定义分页类。这个

Vue是一款流行的JavaScript框架,它提供了许多方便的功能和API以帮助开发者构建交互式的前端应用程序。随着Vue3的发布,render函数成为了一个重要的更新。本文将介绍Vue3中render函数的概念、用途和如何使用它自定义渲染函数。什么是render函数在Vue中,template是最常用的渲染方式,但是在Vue3中,可以使用另外一种方式:r

适用于iPhone的iOS17更新为AppleMusic带来了一些重大变化。这包括在播放列表中与其他用户协作,在使用CarPlay时从不同设备启动音乐播放等。这些新功能之一是能够在AppleMusic中使用交叉淡入淡出。这将允许您在曲目之间无缝过渡,这在收听多个曲目时是一个很棒的功能。交叉淡入淡出有助于改善整体聆听体验,确保您在音轨更改时不会受到惊吓或退出体验。因此,如果您想充分利用这项新功能,以下是在iPhone上使用它的方法。如何為AppleMusic啟用和自定Crossfade您需要最新的

如何在CodeIgniter中实现自定义中间件引言:在现代的Web开发中,中间件在应用程序中起着至关重要的作用。它们可以用来执行在请求到达控制器之前或之后执行一些共享的处理逻辑。CodeIgniter作为一个流行的PHP框架,也支持中间件的使用。本文将介绍如何在CodeIgniter中实现自定义中间件,并提供一个简单的代码示例。中间件概述:中间件是一种在请求

如何在Eclipse中自定义快捷键设置?作为一名开发人员,在使用Eclipse进行编码时,熟练掌握快捷键是提高效率的关键之一。Eclipse作为一款强大的集成开发环境,不仅提供了许多默认的快捷键,还允许用户根据自己的偏好进行个性化的定制。本文将介绍如何在Eclipse中自定义快捷键设置,并给出具体的代码示例。打开Eclipse首先,打开Eclipse,并进入


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
