any idea on how can this be done...

given a class

class Employee
{
int age;
String name;
Date DOB;
}

In another class a function was written like:

Object myFun(Employee obj, String attribute)
{
//return proper attribute value without using conditions like If-Else, ternary or
// conditional operators like && etc.
}
Now if i call:

myFun(obj, “name”);
then this function should return name of Employee from object “obj” which was passed as parameter. So based on name of attribute value, it should return that object’s attribute value.

Maybe you can use something like associative arrays, where you will “map” a given string with the respective parameter, and then on the function call you can simply write:

return obj.associate(/*a string with the parameter name*/);

At least that way, you won’t use any if-else statements…

Bruno

Not sure, but I guess this might be what you want.

import java.lang.reflect.Field;
import java.util.Date;

public class Program
{
    public String str = "Hello";
    private Date date = new Date();
    protected int i = 0;

    public static void main(String[] args)
    {
        try
        {
            // Get the Class object associated with this class.
            Program program = new Program();
            Class progClass = program.getClass();

            // Get the field named str.
            Field strField = progClass.getDeclaredField("str");
            System.out.println("Field found: " + strField.toString());

            // Get the field named date.
            Field dateField = progClass.getDeclaredField("date");
            System.out.println("Field found: " + dateField.toString());

            // Get the field named i.
            Field iField = progClass.getDeclaredField("i");
            System.out.println("Field found: " + iField.toString());
        }
        catch (NoSuchFieldException ex)
        {
            System.out.println(ex.toString());
        }
    }

    public Program()
    {
    }

    public Program(String str, Date date, int i)
    {
        this.str = str;
        this.date = date;
        this.i = i;
    }
}

/*
Output:
Field found: public java.lang.String Program.str
Field found: private java.util.Date Program.date
Field found: protected int Program.i
*/

NB: I didn’t code this. I found this here.

Hi,

I am Trying this your Coding Is Not Working, Some error Occurred


Check out this link

//