1

I want to make a table model which stores entities via a list. Like this;

List list = new ArrayList<Entity>();
list.add(entity);
tableModel.setEntityVector(list);

in the Entity Table Model which extends AbstractTableModel the method getValueAt(int row, int column) should return the value of entity fields according to the row and column values. row represent entity number in the list and the column represent the field number in the entity object. But the problem is that when i use the following code;

Entity entity = list.get(rowCount - 1);
Field[] fields = entity.getClass().getDeclaredFields();

i cant reach fields of the object becouse entity fields must be private. And if i had used getDeclaredMethods() instead of getDeclaredFields() method then i could not reached the method that i want, using column parameter becouse of there are constructors, setters...

My question is that; how can i reach an entity's field values using column parameter of getValueAt(int row, int column) method of AbstractTableModel

5
  • Did you give it a try ? wrote some code for that? Commented Mar 14, 2013 at 19:24
  • Yes it threw an exception saying you cant reach private fileds of entity Commented Mar 14, 2013 at 19:25
  • you can reach to the private field if you know the name of those private field variables.. Commented Mar 14, 2013 at 19:27
  • cant we reach without knowing names? Commented Mar 14, 2013 at 19:31
  • Yes you can, see my Answer.... Commented Mar 14, 2013 at 19:38

2 Answers 2

2

You can access all private fields of a class using getDeclaredFields(). see the code given below:

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

class Private {
    private int i = 20;
    public String s = "java";
    private String name = "Object";
    private ArrayList<String> list = new ArrayList<String>()
    {
        {
            add("Hello");add("World");
        }
    };
}
public class Tester
{
    public static void main(String[] st)throws Exception
    {
        Private  p = new Private();
        Field[] fs = p.getClass().getDeclaredFields();
        for (Field f : fs )
        {
            f.setAccessible(true);
            System.out.println(f.get(p));
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You might be able to use the Bean Table Model.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.