简体   繁体   中英

Get Fields in Java class by Getter Method with annotation

Here is My Model Class

@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;
    }
}

I want to get the field names of the class by passing the Column names annotated in getter methods.

Suppose I have two String values.

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.

I want to get the fields userName and emailId by using that List.

The result can be either in String array or List

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

In your case that would be

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)
    }
}

If that shall work for all possible entities (not editable for you), you will have some problems (Column may be annotated on the fields instead of getter, name may not be explicitly stated in the annotation using default, class may be derived from a base class etc.

You can get this way.

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");

Use Method Reflect and PropertyDescriptor of java.beans

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();
        } 
    }

You might actually want to do

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

Also if you can't use the variable name directly and you have your field names declared in variable annotations, then try playing around a bit with

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

If it's not a sufficient answer for you, then please comment, I will gladly provide further help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM