Annotations are a very important part of Java, but it’s true that they are often overlooked. We say this because we are more likely to be users of annotations than creators. Did you use @override annotation? Did you use the @service annotation? But do you know how to customize a comment?
You’ll probably shake your head, wave your hand, and sheepishly admit that you haven’t.
01. What is a note
Annotations were introduced in Java 1.5 and are a type, along with classes and interfaces. Annotations provide a set of data used to decorate program code (classes, methods, fields, etc.), but annotations are not part of the code being decorated and have no direct effect on how the code behaves. The compiler decides what to do.
Here’s a piece of code, I wrote it randomly, nothing important except the blurb printed to the console. Hee hee.
public class AutowiredTest {
@Autowired
private String name;
public static void main(String[] args) {
System.out.println("Silent King II, a funny programmer."); }}Copy the code
Notice the @autowired annotation? It was supposed to inject beans into the Spring container, and NOW I’ve ruthlessly thrown it at the member variable name, but this code is in a project that doesn’t have Spring enabled, meaning the @AutoWired annotation is just a decoration at this point.
I’m using this boring example to prove a point: annotations have no direct effect on how the code works, see what I mean?
02. The lifecycle of annotations
The lifecycle of an annotation has three policies, defined in the RetentionPolicy enumeration.
1) SOURCE: valid in the SOURCE file, discarded by the compiler.
2) CLASS: valid in bytecode files generated by the compiler, but discarded at run time by the JVM that handles CLASS files.
3) RUNTIME: valid at RUNTIME. This is one of the most common strategies in the annotation lifecycle, allowing applications to access annotations reflectively and execute code based on their definitions.
03, annotation decoration goal
The goal of the annotations defines which level of Java code the annotations will be applied to, some to methods only, some to member variables only, some to classes only, and some to both.
As of Java 9, there are 11 types of annotations, defined in the ElementType enumeration.
1) TYPE: used for classes, interfaces, annotations, enumerations
2) FIELD: Used for fields (member variables of a class), or enumeration constants
3) METHOD
4) PARAMETER: PARAMETER used for common methods or constructors
5) CONSTRUCTOR
6) LOCAL_VARIABLE: used for variables
7) ANNOTATION_TYPE: used for annotations
8) PACKAGE
9) TYPE_PARAMETER: used for generic parameters
10) TYPE_USE: used to declare types in statements, generics, or casts
11) MODULE: used for MODULE
04, start masturbation notes
No matter how much you say, it’s not as exciting as stroking notes. What kind of notes? A field annotation that indicates whether the object should include the field when serialized to JSON.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JsonField {
public String value(a) default "";
}
Copy the code
1) JsonField annotations have a RUNTIME lifecycle, which means they are valid at RUNTIME.
2) JsonField annotation decorators target fields, that is, fields.
3) Create annotations using @interface keyword.
4) The JsonField annotation takes one parameter, named value, of type String, and the default value is an empty String.
Why is the parameter name value? Does it have any special meaning?
Of course, value allows the user of an annotation to provide an argument without specifying a name. For example, we can use @jsonField (value = “Silent King 2 “) on a field, or we can omit value = and change it to @jsonfield (” Silent King 2 “).
So what does “default” mean?
There is, of course, one that allows you to use @jsonField directly on a field without specifying the name and value of the parameter.
05. Use annotations
It’s a mule or a horse out for a walk, right? Now that the @jsonField annotation is handy, it’s time to use it.
Suppose you have an author class that has three fields, age, name, and bookName, the last two of which must be serialized.
public class Writer {
private int age;
@JsonField("writerName")
private String name;
@JsonField
private String bookName;
public Writer(int age, String name, String bookName) {
this.age = age;
this.name = name;
this.bookName = bookName;
}
// getter / setter
@Override
public String toString(a) {
return "Writer{" +
"age=" + age +
", name='" + name + '\' ' +
", bookName='" + bookName + '\' ' +
'} '; }}Copy the code
1) The @jsonField annotation on name provides an explicit string value.
2) The @jsonField annotation on bookName uses the default.
Next, we’ll write the serialization class JsonSerializer, which looks like this:
public class JsonSerializer {
public static String serialize(Object object) throws IllegalAccessException { Class<? > objectClass = object.getClass(); Map<String, String> jsonElements =new HashMap<>();
for (Field field : objectClass.getDeclaredFields()) {
field.setAccessible(true);
if(field.isAnnotationPresent(JsonField.class)) { jsonElements.put(getSerializedKey(field), (String) field.get(object)); }}return toJsonString(jsonElements);
}
private static String getSerializedKey(Field field) {
String annotationValue = field.getAnnotation(JsonField.class).value();
if (annotationValue.isEmpty()) {
return field.getName();
} else {
returnannotationValue; }}private static String toJsonString(Map<String, String> jsonMap) {
String elementsString = jsonMap.entrySet()
.stream()
.map(entry -> "\" " + entry.getKey() + "\", \ "" + entry.getValue() + "\" ")
.collect(Collectors.joining(","));
return "{" + elementsString + "}"; }}Copy the code
The Contents of the JsonSerializer class may seem a bit much, but don’t be afraid to let me explain them a little bit until you get the hang of it.
1) The serialize() method is used to serialize objects, and it takes an Object parameter. ObjectClass. GetDeclaredFields () by the reflection of the way to get all the field of object statement, then a for loop traverse. In the for loop, we first set the accessibility of the reflected object to true via field.setaccessible (true) for serialization (private fields are not available without this step, Throws illegalAccess ception); IsAnnotationPresent () determines whether the field is decorated with a JsonField annotation, and if so, calls the getSerializedKey() method and gets the value represented by this field on the object and places it in jsonElements.
2) The getSerializedKey() method is used to get the value of the annotation on the field, or return the field name if the annotation value is empty.
3) The toJsonString() method returns a formatted JSON string as a Stream. If you are unfamiliar with a Stream Stream, check out the Stream inflow door I wrote about earlier.
After reading my explanation, does it suddenly become clear?
Next, let’s write a test class called JsonFieldTest, with the following contents:
public class JsonFieldTest {
public static void main(String[] args) throws IllegalAccessException {
Writer cmower = new Writer(18."Silent King II."."The Path to Full Stack Development on the Web"); System.out.println(JsonSerializer.serialize(cmower)); }}Copy the code
The program output is as follows:
{"bookName":"The Path to Full Stack Development on the Web"."writerName":"Silent King II."}
Copy the code
From the results:
1) The age field of the Writer class does not decorate the @jsonfield annotation, so it is not serialized.
WriterName (@jsonField); writerName (@jsonField); writerName (@jsonField); writerName (@jsonField);
3) The Writer class’s bookName field is decorated with the @jsonField annotation, but does not explicitly specify a value, so it is still a bookName after serialization.
06, thanks
Well, my dear readers, that’s all for this article. Does it feel easy to masturbate a note? You also quickly move the small hand to try! Original is not easy, do not want a free ticket, please praise for this article, this will be my writing more high-quality articles of the strongest power.
If you think this article is helpful to you, please search “Silent King ii” on wechat and read it for the first time. Reply [666] there is also a 500G HIGH-DEFINITION teaching video (classified) that I prepared for you. Interview on GitHub