--注解Annotation
import java.lang.annotation.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Inherited
@Target(ElementType.FIELD)
@Retention(RUNTIME)
public @interface Attribute {
String name() default "";
}
实体bean用法
调用方法,获取所有属性和注解的值
package com.sic.credit.collection;
import com.sic.credit.api.datacollection.bo.common.ResourceCatalogBo;
import com.sic.credit.api.datacollection.util.Attribute;
import java.lang.reflect.Field;
import java.util.*;
public class test {
public static void main(String[] args) throws Exception{
List<String> headerName = new ArrayList<String>();
List<String> headerKey = new ArrayList<String>();
//得到class
Class clazz = ResourceCatalogBo.class;
//得到所有属性
Field[] fields = clazz.getDeclaredFields();
List<Field> list = new ArrayList<>();
list.addAll(Arrays.asList(fields));
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null) {
Field[] superFields = superClazz.getDeclaredFields();
for (int i=0;i<superFields.length;i++){
//得到属性
Field field = superFields[i];
Attribute fieldAnnotation = field.getDeclaredAnnotation(Attribute.class);
if(fieldAnnotation != null){
//打开私有访问
field.setAccessible(true);
//获取属性
String name = field.getName();
//放入列表中
headerName.add(fieldAnnotation.name());
headerKey.add(name);
} else {
System.out.println("字段"+field.getName()+"没有注解");
}
}
}
System.out.println(headerName.toString());
System.out.println(headerKey.toString());
}
}
输出结果为