应用注解和反射构造ext的grid需要的列模型

使用注解和反射构造ext的grid需要的列模型

注解类:

 

package xzd;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented  
@Inherited  
public @interface FieldsAnnotation {
	String header();
	long width() default 100;
	long hidden();  //1代表显示 0 代表隐藏
}

 

 

一个实体类(内有测试 通过json-lib拼装的数据)

 

package xzd;

import java.lang.reflect.Field;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Dog {
	@FieldsAnnotation(header="姓名",hidden=1)
	public String name;
	
	@FieldsAnnotation(header="地址",width=150,hidden=0)
	public String loc;
	
	@FieldsAnnotation(header="年龄",width=70,hidden=1)
	public long age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLoc() {
		return loc;
	}
	public void setLoc(String loc) {
		this.loc = loc;
	}
	public long getAge() {
		return age;
	}
	public void setAge(long age) {
		this.age = age;
	}
	
	public static void main(String[] args) {
		JSONArray jsonArray = new JSONArray();
		
		Field[] f = Dog.class.getDeclaredFields();
		for(int i =0;i<f.length;i++){
			if(f[i].isAnnotationPresent(FieldsAnnotation.class)){
				FieldsAnnotation fa = f[i].getAnnotation(FieldsAnnotation.class);
				JSONObject jsonObject= new JSONObject();
				jsonObject.accumulate("header",fa.header());
				jsonObject.accumulate("hidden",fa.hidden()==0?true:false);
				jsonObject.accumulate("width",fa.width());
				jsonArray.add(jsonObject);
			}	
		}
		System.out.println(jsonArray.toString());
	}
}
 

   打印结果:

   [{"header":"姓名","hidden":false,"width":100},{"header":"地址","hidden":true,"width":150},{"header":"年龄","hidden":false,"width":70}]

 

另附注解学习文章 :http://yangjunfeng.iteye.com/blog/400085

1 楼 fredzhangjy 2010-09-21  
嗯,不错的方法,学习。。