在 Java class 中打印具有特定注释的字段
print the fileds which has a specific annotation in a Java class
在我的模型中有不同的持久字段,它们具有不同的注释,例如 @Column、@OneToMany 等。
@OneToMany(mappedBy = "Clinte", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Takeover> takeovers = new HashSet<Takeover>();
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "CAR_ID")
private Car carID;
@Column(length = 50, name = "TYPE")
private String type;
如何打印具有注释 @Column 且类型为 String 的持久字段??例如在我的代码中,我只想打印 "type" 因为它有注释 @Column 并且类型为 String.
我已经找到方法了:
Field[] fields=myClass.class.getDeclaredFields();
for (int i=0; i != fields.length; ++i) {
Field field=fields[i];
Column info=field.getAnnotation(Column.class);
if (info == null || field.getType() != String.class){
continue;
}
System.out.println("Field Name : "+ field.getName() + " Field type: " +field.getType().getSimpleName());
}
在我的模型中有不同的持久字段,它们具有不同的注释,例如 @Column、@OneToMany 等。
@OneToMany(mappedBy = "Clinte", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Takeover> takeovers = new HashSet<Takeover>();
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "CAR_ID")
private Car carID;
@Column(length = 50, name = "TYPE")
private String type;
如何打印具有注释 @Column 且类型为 String 的持久字段??例如在我的代码中,我只想打印 "type" 因为它有注释 @Column 并且类型为 String.
我已经找到方法了:
Field[] fields=myClass.class.getDeclaredFields();
for (int i=0; i != fields.length; ++i) {
Field field=fields[i];
Column info=field.getAnnotation(Column.class);
if (info == null || field.getType() != String.class){
continue;
}
System.out.println("Field Name : "+ field.getName() + " Field type: " +field.getType().getSimpleName());
}