3

In Ruby I can get instance variable val with following code

class C
  def initialize(*args, &blk)
    @iv = "iv"
    @iv2 = "iv2"
  end
end

puts "C.new.inspect:#{C.new.inspect} ---- #{::File.basename __FILE__}:#{__LINE__}"
# => C.new.inspect:#<C:0x4bbfb90a @iv="iv", @iv2="iv2"> ---- ex.rb:8

In Java, I expect I can get following result, how should I do?

package ro.ex;

public class Ex {
    String attr;
    String attr2;

    public Ex() {
        this.attr = "attr";
        this.attr2 = "attr2";
    }

    public static void main(String[] args) {
        new Ex().inspect();
        // => Ex attr= "attr", attr2 = "attr2";
    }
}

update:

i find this can solve my question, but i wanna more simple, like some function in guava.in ruby, i primarily use Object#inspect in rubymine watch tool window, i expect i can use it like obj.inspect

update:

i finally determine use Tedy Kanjirathinkal answer and i implement by myself with following code:

package ro.ex;

import com.google.common.base.Functions;
import com.google.common.collect.Iterables;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * Created by roroco on 10/23/14.
 */
public class Ex {
    String attr;
    String attr2;

    public Ex() {
        this.attr = "val";
        this.attr2 = "val2";
    }

    public String inspect() {
        Field[] fs = getClass().getDeclaredFields();
        String r = getClass().getName();
        for (Field f : fs) {
            f.setAccessible(true);
            String val = null;
            try {
                r = r + " " + f.getName() + "=" + f.get(this).toString();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return r;
    }

    public static void main(String[] args) {
        StackTraceElement traces = new Exception().getStackTrace()[0];
        System.out.println(new Ex().inspect());
        // => ro.ex.Ex attr=val attr2=val2
    }
}
Community
  • 1
  • 1
roroco
  • 439
  • 1
  • 6
  • 14

3 Answers3

6

I guess what you want is ReflectionToStringBuilder in Apache Commons Lang library.

In your class, define your inspect() method like as follows, and you should be able to see the expected result:

public void inspect() {
    System.out.println(ReflectionToStringBuilder.toString(this));
}
1

Most common method is to override toString on the class to output whatever the internal state of the class is, and then use it with System.out.println. If you want to do something more automatic, then look up how reflection or introspection can help you. Try BeanUtils.

Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23
0

The equivalent method is Object#toString(), although this gives a useless unreadable jumble unless overriden.

bcsb1001
  • 2,834
  • 3
  • 24
  • 35