geyouchao的专栏

将来的你会感激现在奋斗的你

java中注解例子,使用反射做测试

上一篇博客中讲解了java中注解如何工作的,这章主要讲解自定义注解的例子。

此例子中有三个文件User.java、FieldAnnotation.java、FieldAnnotationTest.java,下面直接上源码。

/**
 * 
 */
package com.test.annotations;


public class User {

	private int id;
	private String name;
	private int age;
	private String country;

	public User(int id, String name, int age, String country){
		this.id = id;
		this.name = name;
		this.age = age;
		this.country = country;
	}
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

}

package com.test.annotations;

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;

@Documented
@Target(value = { ElementType.FIELD,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
	public int id() default 1;
	public String name() default "zhangsan";
	public int age() default 18;
	public String country() default "china";
}

/**
 * 
 */
package com.test.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.reflect.Field;


public class FieldAnnotationTest {

	//注解的使用
	@FieldAnnotation(id = 2014, name = "james", age = 20, country = "usa")
	public Object obj;
	
	public User user;

	public static void main(String[] args) throws Exception {
		Field objField = FieldAnnotationTest.class.getField("obj");
		FieldAnnotation fa = objField.getAnnotation(FieldAnnotation.class);// 得到注解,起到了标记的作用

		System.out.println("-----------obj-------------------");
		System.out.println(fa.id() + "," + fa.name() + "," + fa.age() + "," + fa.country());
		System.out.println("-----------obj-------------------");
		
		//把注解中值赋给user对象
		FieldAnnotationTest tm = new FieldAnnotationTest();
		Field userField = FieldAnnotationTest.class.getField("user");
		userField.set(tm, new User(fa.id(),fa.name(),fa.age(),fa.country()));
		
		System.out.println("-----------user-------------------");
		System.out.println(tm.user.getId() + "," + tm.user.getName() 
				+ "," + tm.user.getAge() + "," + tm.user.getCountry());
		System.out.println("-----------user-------------------");
		
		//注解能获得注解自己的注解
		Target t = fa.annotationType().getAnnotation(Target.class);
		ElementType[] values = t.value();
		for(ElementType etype:values){
			System.out.println(etype.toString());
		}
	}
}




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/geyouchao/article/details/51557205
个人分类: java
上一篇MyEclipse使用Tomcat,报OutOfMemoryError的解决办法
下一篇Java中的注解是如何工作的
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭