What is Java Function Equivalent to Checking Ruby Object #
In Ruby, I can get an instance of the val variable with the 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 to be able to get the following result, how should I do this?
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 want to make it simpler like some functions in guava.in ruby, i use Object # inspect in rubymine watch tool window first of all, i expect i can use it as obj.inspect
update:
Finally, I am using Tedy Kanjirathinkal's answer and I am implementing the following code myself:
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
}
}
source to share
I assume you want ReflectionToStringBuilder in Apache Commons Lang library .
In your class, define your inspect () method as follows and you can see the expected output:
public void inspect() {
System.out.println(ReflectionToStringBuilder.toString(this));
}
source to share
Equivalent method Object#toString()
, although it gives a useless unreadable mess if not exceeded.
source to share