I have below piece of code which is going to get the value from given array list irrespective of data type. And It works fine.
public static <E> void getAll(List<E> elements)
{
for (E el : elements)
{
System.out.println(el.toString());
}
System.out.println();
}
public static void main(String args[]) throws Exception
{
List<Integer> listInt = new ArrayList<Integer>();
listInt.add(3);
listInt.add(4);
listInt.add(5);
listInt.add(6);
List<String> listStr = new ArrayList<String>();
listStr.add("Animal");
listStr.add("Ball");
listStr.add("cat");
listStr.add("dog");
getAll(listInt);
getAll(listStr);
}
Output:
3
4
5
6
Animal
Ball
cat
dog
But I tried the same concept to get the data from POJO object but Its fail and return only object instead of Field as look like above.
The below code is my sample POJO:
public class Test1
{
private String car;
private int price;
public String getCar()
{
return car;
}
public void setCar(String car)
{
this.car = car;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
this.price = price;
}
public String toString()
{
return String.format(car);
}
}
The below code is added into main() method:
Test1 t1 = new Test1();
t1.setCar("volvo");
t1.setPrice(400000);
Test1 t2 = new Test1();
t2.setCar("datsun");
t2.setPrice(500000);
List<Test1> t1Array = new ArrayList<Test1>();
t1Array.add(t1);
t1Array.add(t2);
getAll(t1Array);
And below is the output of the code:
Output:
Volvo
Datsun
Is there any other way to get the value (Integer) of the field, which will works for any type of POJO class.
Any leads?