[Java] Custom annotation Demo

Source: Internet
Author: User

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}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.