1

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       
}
iCode
  • 8,892
  • 21
  • 57
  • 91
  • Are the column names (sometimes) different from the field names? In your example they are not... – Uwe Allner Apr 23 '14 at 08:31
  • Remove the name attributes and use reflection to get the method names. – Stefan Apr 23 '14 at 08:32
  • 1
    see http://stackoverflow.com/q/1805200/492462 – mdo Apr 23 '14 at 08:34
  • @UweAllner They may be same. May be diferent. Usually diferent. Fields start with lowercase. And also might be underscore in some other model class fields.. :) – iCode Apr 23 '14 at 08:42

4 Answers4

2

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.

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
1

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.

Dropout
  • 13,653
  • 10
  • 56
  • 109
  • Capturing the fields in the Model class may not be wise in all cases. Sometimes a model class contains some fields that are not annotated with any column and your solution will get try to retrieve annotations for these fields as well – Saif Asif Apr 23 '14 at 09:03
  • @SaifAsif That's not really a problem IMHO. He would get an empty array and the logic inside the second cycle would not get executed. Am I missing something? – Dropout Apr 23 '14 at 09:08
  • No you are correct on that one. Its just an extra check for a non-annotated field. Why check a non-annotated field for annotations in the first place. – Saif Asif Apr 23 '14 at 09:09
  • @SaifAsif well yes. That's true, in case that there are these types of fields, then checking them is redundant. I won't probably get the correct answer mark, but I'll leave the answer here, it might still help someone. Cheers! – Dropout Apr 23 '14 at 09:12
1

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");
TheDude
  • 3,796
  • 2
  • 28
  • 51
Asif Bhutto
  • 3,916
  • 1
  • 24
  • 21
1

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();
        } 
    }
Coder
  • 6,948
  • 13
  • 56
  • 86