Java equivalent to python “dir”?

前端 未结 2 525
[愿得一人]
[愿得一人] 2021-01-19 21:49

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

相关标签:
2条回答
  • 2021-01-19 22:13

    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

    0 讨论(0)
  • 2021-01-19 22:17

    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.

    0 讨论(0)
提交回复
热议问题