Posted In: Java Core

How to print java object without getting object name like SomeType@

There are three possible ways
1. Override toString method in your class/pojo @Override public String toString()
2. Use org.apache.commons.lang.builder.ToStringBuilder
3, Use Arrays.toString to print values from string array

package com.javausecase.string;

import java.util.Arrays;

import org.apache.commons.lang.builder.ToStringBuilder;

public class ToString {
	public void overrideToString() {
		User user = new User();
		user.setName("Abhijit");
		System.out.println(user);
	}

	public void toStringBuilder() throws Exception {
		User2 user2 = new User2();
		user2.setName("Abhijit");
		System.out.println(
		        ToStringBuilder.reflectionToString(user2));
	}

	public void arraysToString() {
		String[] array = { "a", "b" };
		System.out.println(Arrays.toString(array));
	}

	public static void main(String a[]) throws Exception {
		ToString toString = new ToString();
		toString.overrideToString();
		toString.toStringBuilder();
		toString.arraysToString();
	}
}

class User {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "User [name=" + name + "]";
	}

}

class User2 {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Tags:

by , on October 21st, 2018