What does my own made class need to support in order for println() to print it? For example, I have:
public class A {
...
}
What methods should class A have to make this code work? Maybe something like this:
public static void main() {
A a = new A();
System.out.println(a);
}
I have a guess that the toString() method must be overloaded. Am I right? Is this enough?
You can print any Object using System.out.println(Object). This overloaded version of println will print out toString representation of your object. If you want to customize what will be printed out, you must override the Object#toString() method, for example:
public class A {
private String foo;
#Override
public String toString() {
// When you print out instance of A, value of its foo
// field will be printed out
return foo;
}
}
If you don't override the Object#toString() method, default implementation from Object class will be used, which has this form (class name and the hexidecimal representation of the instance hash code):
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
Bonus: if you need to create toString() implementation from multiple fields, there are tools to make it easier. For instance ToStringBuilder from Commons Lang. Or some Java IDEs like IntelliJ IDEA even offer to generate toString for you based on the class' fields.
You need to provide an override of toString() method for this:
public class A {
#Override
public String toString() {
return "A";
}
}
The method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
You need implement toString() method. Everything you return from it will be printed.
Related
Say I have this enum:
public class MyErrors {
public enum Errors {
BAD_FILE_PATH("Please point to a valid file");
private final String message;
Errors(final String message) {
this.message = message;
}
#Override
public String toString() {
return message;
}
}
And this call:
Logging.log(Level.INFO, MyErrors.Errors.BAD_FILE_PATH.toString());
It seems so verbose to me to have to call .toString(). Isn't there a way to just call the enum itself and have it return its string by default?
Ideally I'd like something like MyErrors.BAD_FILE_PATH --> which returns a string so it's not so verbose. Does that make any sense?
Both of these work for me in Eclipse:
LOG.info(Errors.BAD_FILE_PATH); // Using Log4j
System.out.println(Errors.BAD_FILE_PATH);
These two methods take an Object parameter. And since are not receiving Strings, the logic in those methods must call the toString() method on the passed in object to obtain a string.
The log() method of java.util.logging.Logger does not support an Object parameter. Instead, it is expecting a String parameter; thus, the logic in this method has no need to call toString().
What you are looking for is a new signature for the Logger that supports an Object parameter. However, I don't know that extending the Logger is a straight forward process or advisable; see here.
Another option would be to use Log4j.
I have quite a few getter methods in a class and I need to print the return of those getters (Just one and not all of them at once). I need to be able to do this with one print() method but I am not sure how to do this. Is there a way to dynamically call another method and then print the return of that method?
Here are a couple of getter methods:
public String getEmail()
{
return this.studentEmail;
}
public Integer getAge()
{
return this.studentAge;
}
Here is what I am wanting to do:
public void print(???)
{
System.out.println(theGetterMethod);
}
I know that I can create a bunch of print methods but I need to be able to do this with one method.
As asked by the OP:
"I think you were correct with your first comment and it can be an answer."
From:
"You can tackle it by using Sytem.out.println ("E-mail: " + ...getEmail(), " Age: " + ...getAge()); If you want to go overkill you can use reflection."
Meaning instead of having a seperate print() method you will instead be invoking the right accessor for the value you want to print.
This is one of reasons why you use accessors in the place, as now you are exposing the fields without any risk of having the user change them.
You can still change on underlying Objects apart from String as it is immutable.
You can call methods dynamically based on their name by using reflection.
In this example I assume that each Getter follows a pattern and just pass over the property name that I want to print out:
import java.lang.reflect.Method;
public class Student {
private String studentEmail = "MyEmail";
private Integer studentAge = 20;
public String getEmail() {
return this.studentEmail;
}
public Integer getAge() {
return this.studentAge;
}
// Prints out a property based on the name
public void print(String property) throws Exception {
for (Method method : this.getClass().getMethods())
if (method.getName().equals("get" + property))
System.out.println(method.invoke(this, null));
}
// Prints out all properties with a getter
public void print() throws Exception {
for (Method method : this.getClass().getMethods())
if (method.getName().startsWith("get"))
System.out.println(method.invoke(this, null));
}
}
And than call the method like that:
Student s = new Student();
s.print("Email");
s.print("Age");
I want to generate toString() method for a class extending an other one. But in generate toString() dialog, there is no checkbox for inherited fields (see picture below)
What's the problem here ?
The Inherited fields option will turn out if:
You are extending a class with inheritable fields, i.e. public, protected (or package-protected within the same package)
You are generating the toString method contextually to a right-click when your cursor is within the child class
The latter can be confusing: it's not where you right-click, but where your actual cursor is, that determines for which class the toString (et al.) method should be generated.
You have to write a toString() method in the superclass and then you need to select the inherited method and select toString() there.
Bit late, but consider using the reflectionToString method in the ToStringBuilder class in the Apache Commons library rather than implementing your own toString method for each class. You can use it like this:
public String toString() {
ToStringBuilder.reflectionToString(this)
}
It'll dynamically generate a String based on all the fields in your class, including those in any superclasses.
You can also tune the output a bit if you want different behaviour for some cases (excluding some fields, not including inherited fields etc).
I know this is slightly off-topic, but someone might prefer the following code:
public String toString() {
StringBuilder toReturn = new StringBuilder("\r\n-------------\r\n");
Class<?> c = this.getClass();
toReturn.append(c.getName()).append("\r\n");
Method[] methods = c.getMethods();
for (Method method : methods) {
if (method.getName().startsWith("get") && !method.getName().equals("getClass")) {
Object obj = new String("no value");
try {
obj = method.invoke(this, (Object[]) null);
} catch (Throwable e) {
}
toReturn.append(method.getName()).append(" -> ").append(obj).append("\r\n");
}
}
toReturn.append("-------------\r\n");
return toReturn.toString();
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I am a newbie in java. Say, I have a class Individual. I want to print
Individual ind = new Individual();
System.out.println(ind);
Above code gives output like this:
Individual#1922221
What is the significance of this?
Is it some kind of unique id
for that object?
Can I customize this? I mean write a function of
my own which will give output when I print?
If so, how can I do
this?
If you want to print meaningful content of any object, you have to implement your own toString() method, which will override the parent(Object) class's toString() method. By default all the classes(Whatever you create) extends Object class.
Sample Code:
public class Individual {
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Name of Individual :").append(this.getName())
.append("\nCity :").append(this.getCity());
return builder.toString();
}
public static void main(String[] args) {
Individual individual = new Individual();
individual.setName("Crucified Soul");
individual.setCity("City of Crucified Soul");
System.out.println(individual);
}
}
Output:
Name of Individual :Crucified Soul
City :City of Crucified Soul
If you have bigger class with many variables, you can use XStream to implement your toString() method. XStream will print your object meaningful in XML format. Even you can parse them back to equivalent object. Hope this would help you.
This is the result of default toString() method - the classname + hashcode. This can be override by overriding toString().
Some reference here: http://www.javapractices.com/topic/TopicAction.do?Id=55
Since it hasn't been explained yet, overriding the toString() method simply means that you create a toString() method of your own in your class. By putting your own version of toString() in your class, you make it so that java will use your toString() method rather than the default. Because the original toString() method returns a string, however, your toString() method must also return a string. Your Individual class would look something like this:
public class Individual{
//any other code in the class
public String toString(){
return "your string";
}
}
Then, when you called your System.out.print(ind); it would print out your string.
I think you want to overwrite Individual toString. See http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#toString()
I have a class called ArionFileExtractor in a .java file of the same name.
public class ArionFileExtractor {
public String ArionFileExtractor (String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
However, when I try to invoke ArionFileExtractor in another .java file, as follows:
String afe = ArionFileExtractor("gibberish.txt", "foo", "/foo");
NetBeans informs me that there are incompatible types and that java.lang.String is required. But I coded ArionFileExtractor to return the standard string type, which is java.lang.string.
I am wondering, can my ArionFileExtractor constructor legally return a String?
I very much appreciate any tips or pointers on what I'm doing wrong here.
Constructors create objects, they don't return data.
Your method, ArionFileExtractor(), is not a constructor. Consutructors do not have return types, and look like this:
public ArionFileExtractor (String fName, String startText, String endText) {
//...
}
Note the lack of a return type.
A constructor can only return an instance of object that it constructed - otherwise you have no reference against which to hang on to the object you just created! If you want to make a "utility" call, consider a static method:
public class ArionFileExtractor {
public static String getFileContents(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
Which can be invoked using
ArionFileExtractor.getFileContents(...)
As much as this is surprising, the code you made has a default no argument constructor. ArionFileExtractor is a method that returns a String. I was quite surprised when I first saw code that did this, as it is certainly an accident (as in your case).
You could call you method (just to show this is the case) with:
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
What it really sounds like you are trying to get at is a static method, not a class at all.
public class ArionFileExtractor() {
public static String extract(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
which you would call with:
String afe = ArionFileExtractor.extract("gibberish.txt", "foo", "/foo");
Constructor is not a regular method. It always returns instance of the class that it belongs to. In your example ArionFileExtractor. There is no way to return any other instance.
Notice that you can't specify return type for constructor explicitly nor use return keyword (illegal in this context).
Java compiler treats ArionFileExtractor as an instance method,
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
Constructor can only return instance of its class. It cannot return String.
For instance if you have class SampleClass, constructor can return only object of class SampleClass.
No it should not be able to legally return a String. I'm not sure why Netbeans didn't simply barf at you when you tried to. Maybe it tried to compile it as some sort of static method. Constructors do not generally have return types in code, because when they are compiled they are assigned to return an instance of the class they are constructing.
The easiest (though not necessarily best) way to adapt your code would be to have an empty constructor and turn the current constructor into a static method like this:
public class ArionFileExtractor {
private ArionFileExtractor() {}
public static String ExtractFile(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
The private constructor makes it so that ArionFileExtractor can only be used statically and cannot be instantiated. Then when you use it you simply do this:
String afe = ArionFileExtractor.ExtractFile("gibberish.txt", "foo", "/foo");
Be warned, using static classes is sometimes considered bad form - depending on the situation. So it might be worth while to try and come up with a different way to do this.
No.
A constructor does not really return anything. Instead it builds the object in question.
It looks like you want a utility method here:
public class Whatever {
public static String doStuff(String s) {
return s;
}
}
Yes.Only String class constructor can return string objects out of it ;).
This basically means that the constructor creates the object of the class you are calling.
You need to FIRST create the object (using the constructor) and THEN do stuff with it.
Java has very few smart shortcuts. I