Java equivalent to python "dir"?
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.
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.
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
精彩评论