1

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?

1
  • do you mean passing a "Class object" or simply means passing an "object"? Commented Aug 19, 2013 at 7:57

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

in your method toString() where does person object come from?
Sorry, edit error. person should be this. Fixed in my answer.
If this is what you're looking for, please set this as the accepted answer. :)
0

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.

Comments

0

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

Comments

0

Override the Person class toString method.

public String toString(){
   return "Person:: age:"+age+", name: "+name;
}

1 Comment

you could follow cmbasnett answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.