Get all custom annotations under the specified package
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, ExecutorBean> getRequestMappingMethod(String packageName) { Reflections reflections = new Reflections(packageName); Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Controller.class); // 存放url和ExecutorBean的对应关系 Map<String, ExecutorBean> mapp = new HashMap<String, ExecutorBean>(); 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; } }
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, ExecutorBean> mmap = new HashMap<String, ExecutorBean>(); 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(); } } }
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< T> 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 extends Annotation> T getDeclaredAnnotation(Class < T> 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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



An avatar on Netflix is a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

Google Authenticator is a tool used to protect the security of user accounts, and its key is important information used to generate dynamic verification codes. If you forget the key of Google Authenticator and can only verify it through the security code, then the editor of this website will bring you a detailed introduction on where to get the Google security code. I hope it can help you. If you want to know more Users please continue reading below! First open the phone settings and enter the settings page. Scroll down the page and find Google. Go to the Google page and click on Google Account. Enter the account page and click View under the verification code. Enter your password or use your fingerprint to verify your identity. Obtain a Google security code and use the security code to verify your Google identity.

Annotations in the JUnit framework are used to declare and configure test methods. The main annotations include: @Test (declaration of test methods), @Before (method run before the test method is executed), @After (method run after the test method is executed), @ BeforeClass (method that runs before all test methods are executed), @AfterClass (method that runs after all test methods are executed), these annotations help organize and simplify the test code, and improve the reliability of the test code by providing clear intentions and configurations. Readability and maintainability.

Introduction: PHPDoc is a comment standard for PHP code that produces easy-to-understand and informative documentation. By using specific comment tags, PHPDoc allows developers to provide important details about functions, classes, methods, and other code elements. This advanced guide takes an in-depth look at PHPDoc, demonstrating its capabilities and providing effective documentation strategies. Syntax and tags: PHPDoc comments start with double slashes (//) or multi-line comments (/**/). Here are some common annotation tags: @param: Defines the parameters of a function or method. @return: Specifies the return value of the function or method. @throws: Describes exceptions that may be thrown by a function or method. @var: defines the attributes or instances of the class

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.
