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
}
}