通过带注释的Getter方法获取Java类中的字段

时间:2014-04-23 08:24:25

标签: java

这是我的模型类

@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {

    private Integer userId;
    private String userName;
    private String emailId;
    private String encryptedPwd;
    private String createdBy;
    private String updatedBy;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "UserId", unique = true, nullable = false)
    public Integer getUserId() {
        return this.userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    @Column(name = "UserName", length = 100)
    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Column(name = "EmailId", nullable = false, length = 45)
    public String getEmailId() {
        return this.emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    @Column(name = "EncryptedPwd", length = 100)
    public String getEncryptedPwd() {
        return this.encryptedPwd;
    }

    public void setEncryptedPwd(String encryptedPwd) {
        this.encryptedPwd = encryptedPwd;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    @Column(name = "UpdatedBy", length = 100)
    public String getUpdatedBy() {
        return this.updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }
}

我想通过传递getter方法中注释的Column名来获取类的字段名。

假设我有两个String值。

List<String> columnNames = new ArraList<String>();
columnNames.add("UserName");
columnNames.add("EmailId");

//If you see those Strings are there in getter methods annotated with Column name.

我希望使用该列表获取字段userName and emailId

结果可以是String数组或List

Class clazz = User.class;
for(Method method : clazz.getDeclaredMethods()){
        //What to do here       
}

4 个答案:

答案 0 :(得分:1)

在你的情况下

Class clazz = User.class;
for(Method method : clazz.getDeclaredMethods()){
    Column col = method.getAnnotation(Column.class);
    if(col != null) {
        String columnName = col.name();   // Do with it, whatever you want ;o)
    }
}

如果它适用于所有可能的实体(不能为你编辑),你会遇到一些问题(可能会在字段上注释列而不是getter,使用默认值可能没有在注释中明确说明名称,类可能是派生自基类等。

答案 1 :(得分:1)

你可以这样做。

List<String> columnNames = new ArrayList<>();
        Method[] methods = User.class.getMethods();
        for (Method m : methods) {

            if (m.isAnnotationPresent(Column.class) && m.getName().startsWith("get")) {
                Column annotationNameAtt = m.getAnnotation(Column.class);
                String name= annotationNameAtt.name();
                name = name.substring(0, 1).toLowerCase() +name.substring(1, name.length());
                columnNames.add(name);
            }
// if Column annotaion is not present, here you will get that filed
                if (!m.isAnnotationPresent(Column.class) && m.getName().startsWith("get")) { 
                    String methodName = m.getName();
                    methodName = methodName.substring(0, 1).toLowerCase() +methodName.substring(1, methodName.length());
                    columnNames.add(methodName.replace("get", ""));
                }
            }
if(columnNames.contains("Class")) columnNames.remove("Class");

答案 2 :(得分:1)

使用方法反映和java.beans

PropertyDescriptor
public static void main(String[] args) {

        try {

            Class columnNames = User.class;

            List<String> columnGroups = new ArrayList<String>();
            columnGroups.add("UserName");
            columnGroups.add("EmailId");

            BeanInfo info = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] props = info.getPropertyDescriptors(); //Gets all the properties for the class.

            List<String> modelClassFields = new ArrayList<String>();

            for(String columnField : columnNames){

                for(Method method : clazz.getDeclaredMethods()){

                javax.persistence.Column col = method.getAnnotation(javax.persistence.Column.class); //check for the method annotated with @Column
                if(col != null) {
                    String colName = col.name();
                    if(colName!=null && colName.equals(columnField)) { checking the column attrubute name and the value from given list is equal.
                        for (PropertyDescriptor pd : props) 
                        {  
                            if(method.equals(pd.getWriteMethod()) || method.equals(pd.getReadMethod()))
                            {
                                modelClassFields.add(pd.getDisplayName());
                                System.out.println(pd.getDisplayName());
                            }
                        }
                    }

                }
            }

        }

        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

答案 3 :(得分:0)

您可能真的想要

Field[] fields = User.class.getDeclaredFields();
for(Field f : fields){
    System.out.println(f.getName());
}

此外,如果您不能直接使用变量名称,并且您在变量注释中声明了您的字段名称,那么请尝试使用

// inside the aformentioned cycle
Annotation[] annotations = f.getDeclaredAnnotations();
for(Annotation a : annotations){
    if(){
        // find the correct annotation, parse the name, ???, profit
    }
}

如果这对您来说不够,那么请发表评论,我很乐意提供进一步的帮助。