最近编程时需要按指定的顺序获取JavaBean中的属性和方法,用到了注解和反射。示例代码如下:
MyBean.java
public final class MyBean {
@BeanFieldAnnotation(order = 2)
private String number;
@BeanFieldAnnotation(order = 1)
private String dates;
@BeanMethodAnnotation(order = 1)
public String getNumber() {
return number;
}
//@BeanMethodAnnotation(order = 3)
public void setNumber(String number) {
this.number = number;
}
@BeanMethodAnnotation(order = 2)
public String getDates() {
return dates;
}
//@BeanMethodAnnotation(order = 4)
public void setDates(String dates) {
this.dates = dates;
}
}
BeanFieldAnnotation.java
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanFieldAnnotation {
/**
* 标注该属性的顺序
* @return 该属性的顺序
*/
int order();
}
BeanMethodAnnotation.java
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanMethodAnnotation {
/**
* 标注该属性的顺序
* @return 该属性的顺序
*/
int order();
}
MyBeanTest.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MyBeanTest {
public static void main(String[] args){
MyBean mb=new MyBean();
Field fields[] = mb.getClass().getDeclaredFields();
List<Field> fl=getOrderedField(fields);
Method methods[] = mb.getClass().getDeclaredMethods();
List<Method> ml=getOrderedMethod(methods);
System.out.println("属性");
for(Field f:fl){
System.out.println(f);
}
System.out.println("方法");
for(Method m:ml){
System.out.println(m);
}
}
private static List<Field> getOrderedField(Field[] fields){
// 用来存放所有的属性域
List<Field> fieldList = new ArrayList<>();
// 过滤带有注解的Field
for(Field f:fields){
if(f.getAnnotation(BeanFieldAnnotation.class)!=null){
fieldList.add(f);
}
}
// 这个比较排序的语法依赖于java 1.8
fieldList.sort(Comparator.comparingInt(
m -> m.getAnnotation(BeanFieldAnnotation.class).order()));
return fieldList;
}
private static List<Method> getOrderedMethod(Method[] methods){
// 用来存放所有的方法域
List<Method> methodList = new ArrayList<>();
// 过滤带有注解的方法
for(Method m:methods){
if(m.getAnnotation(BeanMethodAnnotation.class)!=null){
methodList.add(m);
}
}
// 这个比较排序的语法依赖于java 1.8
methodList.sort(Comparator.comparingInt(
m -> m.getAnnotation(BeanMethodAnnotation.class).order()));
return methodList;
}
}