Java equivalent to python “dir”?

谁说胖子不能爱 提交于 2019-12-31 02:24:27

问题


Is there an equivalent to "dir" in python for java, or a library which provides similar functionality (i.e. properties of objects and classes output as informative strings)?

This question is similar this question for clojure and probably has something to do with Java Reflection as in this question, which seems to be about a more complicated, but similar, topic.


回答1:


There's nothing in the standard library that accomplishes exactly what dir() does, but you can get the same information using java.lang.reflect. Specifically, investigating and discovering members of a class is explained in the documentation on discovering class members. Using that API you can easily find out what you need to know about the attributes of a class.

In fact, implementing dir() yourself would just be a matter of defining a method that introspects the methods and fields of a class and either assembles a collection of the info or prints whatever information you'd like to know.

dir() has limited usefulness in Java because Java is not interactive, but if you need it for educational/investigative purposes or for application logic, the reflection API is always there.




回答2:


I was thinking if using javap would be a good choice. The man says javap - The Java Class File Disassembler

and I could see the built in methods by

javap java.lang.Double | grep -i int
public static final int MAX_EXPONENT;
public static final int MIN_EXPONENT;
public static final int SIZE;
public int intValue();
public int hashCode();
public int compareTo(java.lang.Double);
public static int compare(double, double);
public int compareTo(java.lang.Object);

Taking System.out.println(),

javap -c java.lang.System | grep -i out
public static final java.io.PrintStream out;
public static void setOut(java.io.PrintStream);
   4: invokestatic  #4                  // Method setOut0:(Ljava/io/PrintStream;)V
   8: putstatic     #98                 // Field out:Ljava/io/PrintStream;

and then do javap java.io.PrintStream



来源:https://stackoverflow.com/questions/5256001/java-equivalent-to-python-dir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!