find pojo fields by annotation name

时间:2018-06-18 11:37:48

标签: java spring hibernate jsp spring-boot

I had below code I am using Spring.:

 @Entity
@Table(name = "bigcommerce_newsletter_subscriber")
public class BigcommerceNewsletterSubscriberData implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Integer id;

    @Column(name = "account_store_id")
    private Integer accountStoreId;

    @Column(name = "subsciber_id")
    @DataTableHeader(displayName="ID", order=1)
    private Integer subsciberId;

    @Column(name = "email")
    @DataTableHeader(displayName="Email", order=4)
    private String email;

    @Column(name = "first_name")
    @DataTableHeader(displayName="First Name", order=2)
    private String firstName;

    @Column(name = "last_name")
    @DataTableHeader(displayName="Last Name", order=3)
    private String lastName;

    @Column(name = "source")
    @DataTableHeader(displayName="Source", order=6)
    private String source;

now I want all field which contains @DataTableHeader annotation with this annotation.I don't have idea how can I get this. can enyone help me?

3 个答案:

答案 0 :(得分:2)

我们可以使用Class#getDeclaredFields()将所有字​​段设为Field[]。使用Field#getAnnotations(),我们可以将一个特定字段的所有注释都记为Annotation[]

借助这两种方法,问题是可以解决的。以下是使用Java 8 StreamsPredicates的示例实现。

List<Field> allFields = 
    Arrays.asList(BigcommerceNewsletterSubscriberData.class.getFields());
Predicate<Field> isAnnotated = 
    field -> Arrays.asList(field.getAnnotations()).contains(DataTableHeader.class);
List<Field> annotatedFields = allFields.stream()
        .filter(isAnnotated)
        .collect(Collectors.toList());

请注意Collectors.toList() does not guarantee that the returned List is mutable

答案 1 :(得分:1)

You can do it with java reflection

for(Field field : BigcommerceNewsletterSubscriberData.class.getDeclaredFields()){
  Annotation[] annotations = field.getDeclaredAnnotationsByType(DataTableHeader.class);
  if (annotations.length > 0)
    System.out.println(field.getName());
}

Just filter fields, that have annotation you want.

答案 2 :(得分:0)

您还可以使用reflections库来提供一组用于在Java中进行反射的实用程序。要获取包含特定注释的字段列表,可以尝试以下操作:

Reflections reflections = new Reflections("my.project");
Set<Field> fields = reflections.getFieldsAnnotatedWith(DataTableHeader .class);

如果您正在使用maven,请尝试将此添加到您的pom依赖项:

<dependency>
   <groupId>org.reflections</groupId>
   <artifactId>reflections</artifactId>
    <version>0.9.11</version>
</dependency>