1. Custom annotations
package 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.method)
@Retention (retentionpolicy.runtime)
@Documented public
@interface myannotation {
String name ();
int age ();
Boolean sex ();
}
2. Use annotations
package annotation;
Import Java.lang.reflect.Method;
public class Student {
private String name;
private int age;
Private Boolean sex;
public void Init (String name, int age, Boolean sex) {
this.name = name;
This.age = age;
This.sex = sex;
}
@MyAnnotation (name = "John", age = \ Sex = true) public
void Init () {
try {method method
= STUDENT.CLASS.G Etmethod ("Init");
if (Method.isannotationpresent (Myannotation.class)) {
Myannotation anno = method.getannotation ( Myannotation.class);
THIS.name = Anno.name ();
This.age = Anno.age ();
This.sex = Anno.sex ();
}
} catch (SecurityException e) {
e.printstacktrace ();
} catch (Nosuchmethodexception e) {
E.printstacktrace ();
}
public void Show () {
System.out.print ("{name=" + this.name);
System.out.print (", age=" + this.age);
System.out.println (", sex=" +) + (this.sex? "Male": "female") + "}");
}
3. Test
package annotation;
public class Studenttest {public
static void Main (string[] args) throws Exception {Student
stu = new Student (); C3/>stu.init ();
Stu.show ();
Stu.init ("Dick", false);
Stu.show ();
}
4. Print Results
{name= john, age=20,sex= man}
{name= dick, age=21,sex= female}