Reputation: 3843
How can I log class variables and its values dynamically?
Is there any way I can print variable names and its value dynamically by using only class object?
Like for example:
We pass Person
class object and output is:
Person:: age:10, name: abc
something like that..
EDIT:
There are many classes. Any other solution other than Overriding toString()
method? Can it all be dynamic. Like just passing the class object?
Upvotes: 1
Views: 2371
Reputation:
You'll want to use something common in managed languages called reflection. Reflection allows you to know about the internals of the program at run-time.
In Java, you'll want to use the getFields() function on your class (or any other class).
@Override
public String toString() {
for(Field field : this.getClass().getFields()) {
System.out.println(field.getName() + ":" + field.get(this) + ",");
}
}
This allows you to add new fields without the need for updating thetoString()
functions.
Upvotes: 2
Reputation: 41210
Override the Person
class toString
method.
public String toString(){
return "Person:: age:"+age+", name: "+name;
}
Upvotes: 0
Reputation: 48404
I believe you want to override Object.toString
.
Then you can add whatever descriptive field or class name reference you want in the String
returned.
Then if you want to log your class dynamically to whatever logger you use (or simply, System.out
) you can add an instance statement (possibly after the constructor executed) and log the String
representation of your class there.
For instance:
public class Foo {
private int blah;
public Foo() {
blah = 1;
System.out.println(this);
}
@Override
public String toString() {
return getClass().getName().concat(": ").concat(String.valueOf(blah));
}
}
public class Main {
public static void main(String[] args) {
new Foo();
}
}
Output:
test.Foo: 1
Upvotes: 0
Reputation: 68715
If you override toString
method and use Person class in sysout
statements, its toString
will be called internally. So override the toString method to print the object as you mentioned.
Upvotes: 0