Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Java function equivalent to Ruby Object#inspect

Tags:

java

ruby

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
    }
}
like image 448
roroco Avatar asked Mar 04 '26 06:03

roroco


1 Answers

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));
}
like image 190
Tedy Kanjirathinkal Avatar answered Mar 05 '26 20:03

Tedy Kanjirathinkal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!