【发布时间】:2014-12-19 07:36:29
【问题描述】:
在 Ruby 中,我可以使用以下代码获取实例变量 val
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
在Java中,我希望我能得到以下结果,我该怎么办?
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";
}
}
更新:
我发现this 可以解决我的问题,但我想要更简单,比如 guava.in ruby 中的一些功能,我主要在 rubymine 监视工具窗口中使用 Object#inspect,我希望我可以像 obj.inspect 一样使用它
更新:
我最终确定使用 Tedy Kanjirathinkal 的答案,我自己使用以下代码实现:
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
}
}
【问题讨论】:
-
你不能把它(例如,链接中的代码)放到一个函数中吗?