Tag: string representing value equal retention type document SRC round
One, custom Note 1. Use keyword @interface2. By default, annotations can be decorated with classes, methods, interfaces, and so on. 3. The following is an example of a basic annotation:
//注解中的成员变量非常像定义接口
public @interface MyAnnotation {
//不带有默认值
String name();
//带有默认值
int age() default 20;
}
4. Interpretation of 3 common methods in reflect
- Getannotion (class<t> annotationclass) returns an annotation of the specified type that exists on the element, if no null is returned
- Annotation[] Getannotations () returns all annotations on this element.
- Boolean isannotationpersent (class<? extends Annotation> Annotationclass) determines whether the court contains notes on the type of formulation.
Two, Yuan annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValueBind {
filedType type();
String value() default "SUSU";
enum filedType {
STRING, INT
}
}
Where @target and @Retention are the meta annotations.
- There are several values @Retention:
- These are usually retentionpolicy.runtime.
There are several values for @Target:
@Inherited indicates that the annotation is inherited. Third, Demo
1. Valuebind annotations
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueBind {
filedType type();
String value() default "SUSU";
enum filedType {
STRING, INT
}
}
2. Person class
public class Person implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
@ValueBind(type = ValueBind.filedType.STRING, value = "LCF")
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@ValueBind(type = ValueBind.filedType.INT, value = "21")
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}
3. Main method
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Object person = Class.forName("Person").newInstance();
//以下获取的是:类的注解
// Annotation[] annotations = person.getClass().getAnnotations();
Method[] methods = person.getClass().getMethods();
for (Method method : methods) {
//如果该方法上面具有ValueBind这个注解
if (method.isAnnotationPresent(ValueBind.class)) {
//通过这个注解可以获取到注解中定义的
valuebind
annotation
=
method
getannotation valuebind class
if (annotation.type().equals(ValueBind.filedType.STRING)) {
method.invoke(person, annotation.value());
} else {
method.invoke(person, Integer.parseInt(annotation.value()));
}
}
}
System.out.println(person);
}
}
Output: Person{name= ' LCF ', age=21}
Java Annotations Annotation Learning notes