0

I need to capture field name of getter method dynamically for dynamic validation and dynamic formatting. What is the best and efficient way of doing this.

public class Emp{
    private String firstName;
    private String lastName;
    private String address;
    private int age;

    // getter and setters
}


public class MyImplementationClass{

    public execute(Emp emp){
        String fName=emp.getFirstName();
        // field name need to be taken here using 'emp.getFirstName()'
        // need field name and value of return value of 'emp.getFirstName()' for dynamic validation and dynamic formatting.
        // here need to call method validateAndFormat() with field name and value.
    }
}

private String validateAndFormat(String fieldName,String value){
 // read the dynamic validation settings from the xml and  validate/reformat the value
 // this method will validate the field according to xml and return reformatted value.
}
private int validateAndFormat(String fieldName,int value){
//...
}

dynamic validation settings

<message>
    <element field="firstName" length="22" defaultVal=""></element>
    <element field="lastName" length="20" defaultVal="ibft"></element>
    <element field="address" length="NA" defaultVal=""></element>
    <element field="age" length="NA" defaultVal=""></element>
</message>
Dinesh Appuhami
  • 710
  • 1
  • 11
  • 24
  • Please be more specific. I can't understand from your example what is it that you really want. If you call getFirstName then you want to find out dynamically what field is being returned by that method, even if the field isn't called like the method name? – Cristian Bidea Feb 01 '19 at 07:24
  • But `emp.getFirstName()` would return the first name, not the field - it might not even be backed directly by a field. The field is an implementation detail, which you shouldn't need to care about. Could you give more information about what you're trying to achieve? What would the rest of your code look like if you *did* have the field name? – Jon Skeet Feb 01 '19 at 07:24
  • I need the field name and the value of getter for validation and reformatting.. – Dinesh Appuhami Feb 01 '19 at 07:38
  • I can't understand what you want, but if you to need to get the method name I found semiliar question about reflection api here's the [link](https://stackoverflow.com/questions/3023354/how-to-get-string-name-of-a-method-in-java). – Ardika Rommy Sanjaya Feb 01 '19 at 08:18

3 Answers3

0

use getMethods get all public methods of the emp

then choose getXXX method and invoke it

        Emp emp = new Emp();
        emp.setAddress("myAdress");
        emp.setAge(20);
        emp.setFirstName("myFirstName");
        emp.setLastName("myLastName");
        Class clz = emp.getClass();

        Method[] methods = clz.getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if (!Objects.equals(methodName, "getClass")
                    && methodName.startsWith("get")
                    && methodName.length() > 3
                    && method.getParameterTypes().length == 0) {

                String field = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                Object value = method.invoke(emp);
                System.out.println("field:" + field + ",value:" + value);
            }
        }

you can also use getDeclaredFields get all private fields

and find getXXX method by field

        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            try {
                Method method = clz.getMethod(methodName);
                Object value = method.invoke(emp);
                System.out.println("field:" + fieldName + ",value:" + value);
            } catch (NoSuchMethodException e) {
                System.out.println("no such method:" + methodName);
            }
        }
chao.xie
  • 11
  • 2
0

You can use Java reflection. But getting the field name from getter might not be a good design as the getter may not be backed by a field. Consider the below getter.

public int getExp(){
    return today-joiningDate();
}

This is not backed by a field.

Instead, if you want only the field name and value, you can achieve as below.

Class class1 = employee.getClass();
Field[] fields= class1.getDeclaredFields();
    for(Field field:fields){
        try {
            field.setAccessible(true);
            System.out.println(field.getName()+":"+field.get(bean));
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

Hope this helps.

Anitha.R
  • 344
  • 2
  • 15
0

annotation would be a choose.

public @interface MyField {
    String fieldName() default "";
}

and use it on you method

@MyField("firstName")
getFirstName(){
   ...
}

then get fieldName by reflection. i think this way is more flexible than generate field name from method name.

denny
  • 44
  • 2