user2838595
user2838595

Reputation:

How to access field values of a derived class from it's base class in java?

I want to access fields of a derived class from it's base class in java without knowing the name of fields. For what purpose? I want to have a "table" class to manage database tables like INSERT,UPDATE. I a derived class to have only fields and values, and in the base class I read that fields and values and create proper INSERT or UPDATE commands.

I can do this in C# this way:

for (int count = 0; count < finfo.Length; count++)
{
    value = finfo[count].GetValue(this);
    name = finfo[count].Name;
}

I can read field names and type in java like this:

for (Field f : getClass().getDeclaredFields()){
    name = f.getName();
}

but I don't know how to read the VALUE of that field!

I'm asking this question in different ways in many forums but I'm getting no answer! Please help me. thanks in advance.

Upvotes: 0

Views: 1629

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122414

Given a Field f you can read the value of that field in a particular object using f.get(object)

for (Field f : getClass().getDeclaredFields()){
    name = f.getName();
    value = f.get(this);
}

get returns Object - if the field is of a primitive type (boolean, char, int, etc.) then the corresponding wrapper (Boolean, Character, Integer, ...) will be returned (or you can use the type-specific getBoolean, getChar, etc. methods to return the primitive type directly). The get method can throw various exceptions (some checked and some unchecked) which you'll have to handle appropriately, see the JavaDoc for details.

But to step back from your specific question, if your goal is to map classes to database tables then there are mature, well-tested frameworks that can do all the hard work for you, such as Hibernate or one of the many implementations of JPA, and I would strongly recommend you look into one or more of those before you try and roll your own.

Upvotes: 5

RamonBoza
RamonBoza

Reputation: 9038

In your base class, which will be declared as abstract, you can declare an abstract method that will get the values

public abstract BaseClass{
    protected abstract FieldInfo getFieldInfo(i);

    public void doSomething(){
        for (int count = 0; count < finfo.Length; count++)
        {
            FieldInfo finfo = getFieldInfo(count);
            value = finfo.GetValue(this);
            name = finfo.Name;
        }
    }
}

And in your InheritedClass you will have to implement it.

Upvotes: 0

Related Questions