- Как переопределить метод toString() в Java
- 1. Использование оператора конкатенации строк
- 2. Использование ‘StringJoiner’
- 3. Использование Guava ‘MoreObjects.ToStringHelper()’
- 4. Использование Apache Commons ‘ToStringBuilder’ class
- Java — Super.toString() method in base class?
- Java — Super.toString() method in base class?
- How make toString() method return Super Class private fields also along with its instance fields?
- Implementing inheritance overriding the toString method
Как переопределить метод toString() в Java
The toString() метод возвращает строковое представление объекта. Он широко используется для отладки, печати содержимого объектов в журналах и т. д. В этом посте мы обсудим, как переопределить toString() метод в Java.
Класс объектов уже содержит toString() метод, который возвращает строку, которая “текстуально представляет” объект. Реализация по умолчанию Object.toString() метод возвращает строку, состоящую из имени класса, ‘@’ символ, за которым следует беззнаковое шестнадцатеричное представление хеш-кода объекта. т.е.,
Поскольку все объекты Java наследуются от java.lang.Object , вам нужно переопределить toString() метод для получения желаемого строкового представления. В противном случае приведенная выше реализация по умолчанию toString() метод будет вызываться при попытке распечатать объект. Например,
Чтобы напечатать содержимое объекта, ваш класс должен переопределить toString() метод. Это можно сделать несколькими способами:
1. Использование оператора конкатенации строк
Вы можете использовать оператор конкатенации строк + четко и лаконично добавлять переменные-члены в класс. Хотя конкатенация строк с использованием + оператор не рекомендуется в Java, но может быть выполнен без цикла, поскольку компилятор Java неявно создает промежуточный StringBuilder объект.
результат:
Country
2. Использование ‘StringJoiner’
В Java 8 и выше мы можем использовать StringJoiner class, который принимает разделитель и создает последовательность значений, разделенных разделителем.
результат:
Country[name='United States', continent='North America', population=331449281]
3. Использование Guava ‘MoreObjects.ToStringHelper()’
Guava’s MoreObjects class предоставляет несколько вспомогательных функций, которые работают с любым объектом Java. Для реализации Object.toString() метод, вы можете создать экземпляр MoreObjects.ToStringHelper , и позвоните add(name, value) метод для каждого поля. add(name, value) Метод добавляет пару имя-значение к выходным данным в формате имя=значение.
Если вам просто нужно добавить безымянное значение к выводу, вызовите метод addValue(value) метод. Кроме того, вы можете игнорировать свойства с нулевыми значениями, используя omitNullValues() метод.
результат:
Country
4. Использование Apache Commons ‘ToStringBuilder’ class
Похож на Guava MoreObjects класс, библиотека Apache Commons Lang предоставляет ToStringBuilder класс для помощи в реализации Object.toString() методы. Чтобы использовать этот класс, напишите следующий код:
результат:
[email protected][name=United States,continent=North America,population=331449281]
Кроме того, вы можете напрямую вызвать reflectionToString() метод, который использует отражение для создания toString для указанного объекта. Обратите внимание, что этот метод может не работать под управлением менеджера безопасности, поскольку он использует AccessibleObject.setAccessible изменить видимость частных полей в классе.
результат:
[email protected][continent=North America,name=United States,population=331449281]
Обратите внимание, что почти все IDE (Eclipse, IntelliJ IDEA и т. д.) предлагают поддержку автоматического создания toString() метод, основанный на переменных-членах в классе. Рекомендуется использовать соответствующие функции IDE для создания toString() вместо того, чтобы писать его самостоятельно. Например, в IntelliJ IDEA вы можете просто щелкнуть правой кнопкой мыши исходный код, выбрать меню «Создать» и выбрать параметр toString. Либо просто нажмите Alt+Insert и выберите параметр toString.
Кроме того, IntelliJ IDEA предлагает гибкость выбора между различными шаблонами toString, такими как StringBuilder, ToStringBuilder (Apache commons-lang 3), Objects.toStringHelper (Guava), MoreObjects.toStringHelper (Guava 18+), StringJoiner (JDK 1.8), String concat (+ ), так далее.
Это все о переопределении toString() метод в Java.
Средний рейтинг 5 /5. Подсчет голосов: 16
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Java — Super.toString() method in base class?
Solution 1: Your class Person should extend parent class where you define method toString(), otherwise your parent class is class Object and the native method of this class is going to be used: So, you will get a string that consisting of the name of the class of which the object is an instance, the at-sign @, and unsigned hexadecimal representation of the hash code of the object It’s recommended that all classes (subclasses of class Object) override this method. Solution 2: It’s perhaps not related to the question itself, but I think the design could be refined like this: define abstract class Role with the name of role define classes Student, Employee, Staff whatever inheriting Role define class Person with common properties for all person type, names etc, and having property of type Role inside then define toString on Person and in all Role implementation in this way you will be able to extend or modify Persons independently from Roles, which makes the design more flexible Solution 3: The constructor of Person requires a String as third argument, but you are trying to pass to the super-constructor in your sub-classes.
Java — Super.toString() method in base class?
Your class Person should extend parent class where you define method toString(), otherwise your parent class is class Object and the native method of this class is going to be used:
So, you will get a string that consisting of the name of the class of which the object is an instance, the at-sign @, and unsigned hexadecimal representation of the hash code of the object It’s recommended that all classes (subclasses of class Object) override this method.
super keyword is used to call parent class methods in case of inheritance.
Every class is the child of Object class in java and one of its non-final methods is toString() .
So super.toString() calls Object class method toSting() .
String toString() Method in java with Examples, String toString () is the built-in method of java.lang which return itself a string. So here no actual conversion is performed. Since toString () method simply returns the current string without any changes, there is no need to call the string explicitly, it is usually called implicitly. Parameter: The method does not …
How make toString() method return Super Class private fields also along with its instance fields?
If you create getters and setters in your superclass then you can acces the variables through those methods. Other possibility is to change the visibility from private to protected
first solution looks like this
public class Employee < private String name; private int id; private double salary; public Employee(String name, int id, double salary) < super(); this.name = name; this.id = id; this.salary = salary; >public double getSalary() < return salary; >public String getName() < return name; >public void setName(String name) < this.name = name; >public int getId() < return id; >public void setId(int id) < this.id = id; >public void setSalary(double salary) < this.salary = salary; >@Override public String toString() < return "Employee [name=" + name + ", + id + ", salary=" + salary + "]"; >>
public class Manager extends Employee < private double bonus; public Manager(String name, int id, double salary, int bonus) < super(name, id, salary); this.bonus = bonus; >public double getSalary() < double baseSalary = super.getSalary(); return (baseSalary + baseSalary * (bonus / 100)); >@Override public String toString() < return "Manager [name=" + getName() + ", + getId() + ", salary=" + getSalary() + ", bonus=" + bonus + "]"; >>
Second one (using protected)
public class Employee < protected String name; protected int id; protected double salary; public Employee(String name, int id, double salary) < super(); this.name = name; this.id = id; this.salary = salary; >public double getSalary() < return salary; >@Override public String toString() < return "Employee [name=" + name + ", + id + ", salary=" + salary + "]"; >>
public class Manager extends Employee < protected double bonus; public Manager(String name, int id, double salary, int bonus) < super(name, id, salary); this.bonus = bonus; >public double getSalary() < double baseSalary = super.getSalary(); return (baseSalary + baseSalary * (bonus / 100)); >@Override public String toString() < return "Manager [name=" + name + ", + id + ", salary=" + salary + ", bonus=" + bonus + "]"; >>
Personally i’d use the getter/setter method but it’s up to you.
EDIT: Additonal to eclipse generation of toString() in eclipse. You can’t seem to generate it with getters and setter (just had a quick look, you can see some documentation here. What I did figure out is how you can edit the Code Template used when generating the toString() so it includes the toString() from the superclass.
When you enter the generate toString() dialog there is a field ‘String Format’ with next to it. when you click the edit button you can create a new Code Template. This template automatically holds the and should look something like this:
only thing you’ll have to add is the following at the end
This way it’ll display the toString() form the superclass
You can let eclipse generate it, however it would not look like you want it.
Manager [bonus=10.0, toString()=Employee [name=Bill, salary=5000.0]]
That’s the most you can make eclipse generate for you.
You can clean it up a little so it would look like this
Manager [bonus=10.0] is a Employee [name=Bill, salary=5000.0]
However, your custom solution works as well. So why not use it?
You can clean it up a little like this:
@Override public String toString() < return "Manager [" + superFieldsFromToString() + ", bonus=" + bonus + "]"; >private String superFieldsFromToString() < String superToString = super.toString(); int superClassNameLength = getClass().getSuperclass().getSimpleName().length(); int fieldStartIdx = superClassNameLength + 2; // + 2 removes " [" int fieldEndIdx = superToString.length() - 1; // - 1 removes "]" return superToString.substring(fieldStartIdx , fieldEndIdx); >
The only other options, as others have mentioned, are to use reflection to access the private fields, make the fields protected or create public getters.
I would not advice to do any of this, as your class design should not be defined by debug output.
No. Because if you could directly access private fields of super class, those fields would not be private.
Class toString() method in Java with Examples, Return Value: This method returns the String representation of this object. Below programs demonstrate the toString () method. Example 1: public class Test <. public static void main (String [] args) throws ClassNotFoundException. <. Class c1 = Class.forName ("java.lang.String"); …
Implementing inheritance overriding the toString method
The reason you are getting those errors is that the constructors don’t exist.
error: constructor Student in class Student cannot be applied to given types; error: no suitable constructor found for Employee(String,String,String,String)
That means you will not get the code to compile until you have this:
Student(String name, String addr, String phone, String email)
Assuming you have set the properties in the constructor, toString would look like this:
Your problem is that Student has only this constructor:
public Student(String name, String address, int phone, String email, String classStatus)
Student needs a constructor which takes only four strings as its parameters. Alternatively, you can make everything take the five parameters you specified.
It’s perhaps not related to the question itself, but I think the design could be refined like this:
- define abstract class Role with the name of role
- define classes Student, Employee, Staff whatever inheriting Role
- define class Person with common properties for all person type, names etc, and having property of type Role inside
then define toString on Person and in all Role implementation
in this way you will be able to extend or modify Persons independently from Roles, which makes the design more flexible
The constructor of Person requires a String as third argument, but you are trying to pass int phone to the super-constructor in your sub-classes. That won’t work because it’s the wrong type.
By the way: you should always represent phone numbers with strings, not with integers.
- It doesn’t make sense to add or subtract phone numbers.
- Integers don’t allow leading zeros, which are used for area codes in some countries.
- Integers can’t be larger than 2147483648. When you try to store very long telephone numbers, this seemingly arbitrary limit will cause very unexpected bugs.
How to use the toString method in Java?, The default implementation of toString () in class Object returns a string consisting of the class name of this object followed by @ sign and the unsigned hexadecimal representation of the hash code of this object using the following logic, getClass ().getName () + «@» + Integer.toHexString (hashCode ()) …