Question

I have a requirement where i have to print the values which are getting saved in a database. I have pojo object which i am passing it in a list and then saving the entire list in database. Please find the below code.

List dataList=new ArrayList();
Vehicles vehiclePojoObject=new Vehicles();
vehiclePojoObject.setName("Cycle");
vehiclePojoObject.setColor("Blue");
dataList.add(vehiclePojoObject);

Now i have to print the values which is contained by vehiclePojoObject. How can it be acheived. Please guide. Thanks in advance.

Note: There are not one object but multiple objects which are getting stored in the list.

Was it helpful?

Solution 4

Assuming that you want to store objects of different types on the same list and have a single method for printing all private fields of those object regardless of their types you can use the (reflection API). By the help of reflection we can change behavior of list at runtime

OTHER TIPS

Other than the solution posted by @McMonster, you could also make sure that your POJO's override the toString() method so that you can print a customized, and most likely, more readable string representation of your object.

Add vehiclePojoObject to the Vehicles List object, like

List<Vehicles> vehList = new ArrayList<Vehicles>();
Vehicles vehiclePojoObject=new Vehicles();
vehiclePojoObject.setName("Cycle");
vehiclePojoObject.setColor("Blue");
vehList.add(vehiclePojoObject); //Here we are adding pojoObject to list object

And get Vehicles List data through for-each

i.e.

for(Vehicles vehicle : vehList){
  System.out.println("Vehicle Name: "+veh.getName());
  System.out.println("Vehicle Color: "+veh.getColor());
}

Expanding on @npinti answer of overriding toString()

In your POJO file, add this function:

@Override
public String toString() {
    String output = "Name: " + getName() + " Color: " + getColor +
        " Model: " + getModel() + ....;

    return output;
}

then you can loop through your list to and call .toString() on all the objects to print out all of the features

for(Vehicles vehicle : vehList){
     System.out.println(vehicle.toString());
}

List dataList = new ArrayList<>();

    // Print the name from the list....
    for(Vehicles vehicle: Vehicles) {
        System.out.println(vehicle.getName());
        System.out.println(vehicle.getColor());
    }

Hope this helps!!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top