This Java application demonstrates the use of reflection to manipulate fields annotated with custom annotations. The example shows how to inject random values into an object's fields based on the parameters defined in a custom annotation.
The Main class serves as the entry point for the application. It creates a Student object, uses the RandomNumberInjector to inject random values into annotated fields, and then prints the student's details to the console.
The RandomNumber annotation defines two parameters: min and max, which specify the range for the random number generation. Fields annotated with @RandomNumber will be assigned a random value within this range.
The RandomNumberInjector class contains the logic for injecting random numbers into fields annotated with RandomNumber. It uses reflection to:
- Scan the object's fields for the
@RandomNumberannotation. - Generate a random value within the specified range.
- Set the generated value to the corresponding field.
The Student class represents a student with the following fields:
name: The student's name.grade: The student's grade level.score: The student's score, which is annotated with@RandomNumber. A random value is injected into this field.age: The student's age.
The application creates a Student object and passes it to the RandomNumberInjector. The injector scans the object's fields and assigns a random value to any field annotated with @RandomNumber. This demonstrates how annotations can be used to drive custom behavior in a program.