A Java class method extractor

Source: Internet
Author: User
Tags exit class definition constructor final object serialization reflection

There is little need to use reflection tools directly; they are provided in the language only to support other Java features, such as Object serialization (chapter 10th), Java beans, and RMI (described later in this chapter). However, many times we still need to dynamically extract data related to a class. A particularly useful tool is a class method extractor. As noted earlier, if the view class defines a source code or an online document, you can see only the methods defined or overridden in that class definition, where there is still a large amount of data to be found in the underlying class. Fortunately, "reflection" does this, and it can be used to write a simple tool that automatically shows the entire interface. The following are the specific procedures:
 

: Showmethods.java//Using Java 1.1 reflection to show all the//methods of a class, even if the methods are//DEF
Ined in the base class.

Import java.lang.reflect.*;
    public class Showmethods {static final String usage = "Usage: \ n" + "Showmethods qualified.class.name\n" + "To show all methods in class or: \ n" + "Showmethods qualified.class.name word\n" + "to search for methods Involvi
  ng ' word ';
      public static void Main (string[] args) {if (Args.length < 1) {System.out.println (usage);
    System.exit (0);
      try {Class c = class.forname (Args[0]);
      method[] m = C.getmethods ();
      Constructor[] ctor = c.getconstructors ();
        if (args.length = = 1) {for (int i = 0; i < m.length i++) System.out.println (m[i].tostring ());
      for (int i = 0; i < ctor.length i++) System.out.println (ctor[i].tostring ()); else {for (int i = 0; i < m.length; i++) if (m[I].tostring (). IndexOf (Args[1])!=-1) System.out.println (m[i].tostring ()); for (int i = 0; i < ctor.length i++) if (ctor[i].tostring (). IndexOf (args[1))!=-1) Sy
      Stem.out.println (Ctor[i].tostring ());
    The catch (ClassNotFoundException e) {System.out.println ("No such class:" + E); }
  }
} ///:~

Class methods GetMethods () and GetConstructors () can return an array of method and constructor, respectively. Each class provides a further way to resolve the name, parameters, and return values of the method they represent. But you can also use ToString () just like this to generate a string containing the full method signature. The rest of the code is used to extract command-line information, determine if a particular signature matches our target string (using indexof ()), and print out the results.
The "reflection" technique is used here because the results generated by Class.forName () are not known during compilation, so all method signature information is extracted during runtime. If you look at the part of the text in the online documentation about reflection (Reflection), you'll find that it has provided enough support to actually set up and emit method calls for objects that are completely unknown at compile time. Again, this is a step that is almost entirely without our concern.--java will take advantage of this support, so the programming environment can control the Java beans--but it is very interesting anyway.
An interesting experiment is to run the Java showmehods showmethods. This will get a list that includes a public default builder, although we see no builder defined in the code. What we see is the builder that is automatically synthesized by the compiler. If you subsequently set Showmethods as a non-public class (that is, a "friendly" class), the resultant default builder will not appear in the output result. The resultant default builder automatically obtains the same access rights as the class.
Showmethods's output is still somewhat "unpleasant". For example, the following is part of the output results obtained by invoking the Java Showmethods java.lang.String:

public boolean 
  Java.lang.String.startsWith (java.lang.string,int) public
Boolean 
  Java.lang.String.startsWith (java.lang.String) public
boolean
  java.lang.String.endsWith (java.lang.String )

If you can remove qualifiers such as Java.lang, the result is obviously more satisfying. In view of this, the Streamtokenizer class introduced in the previous chapter can be introduced to solve this problem:
 

: Showmethodsclean.java//Showmethods with the qualifiers stripped/to make the results easier to read import JAVA.L
ang.reflect.*;

Import java.io.*; public class Showmethodsclean {static final String usage = "Usage: \ n" + "Showmethodsclean qualified.class.name \ n "+" to show all methods in class or: \ n "+" Showmethodsclean qualif.class.name word\n "+" to search for met
  Hods involving ' word ';
      public static void Main (string[] args) {if (Args.length < 1) {System.out.println (usage);
    System.exit (0);
      try {Class c = class.forname (Args[0]);
      method[] m = C.getmethods ();
      Constructor[] ctor = c.getconstructors ();
      Convert to an array of cleaned strings:string[] n = new String[m.length + ctor.length];
        for (int i = 0; i < m.length i++) {String s = m[i].tostring ();
      N[i] = Stripqualifiers.strip (s); for (int i = 0; i < ctor.length i++) {String s =Ctor[i].tostring ();
      N[i + m.length] = Stripqualifiers.strip (s);
      } if (Args.length = 1) for (int i = 0; i < n.length i++) System.out.println (n[i)); else for (int i = 0; i < n.length i++) if (N[i].indexof (args[1))!=-1) System.out.println
    (N[i]);
    catch (ClassNotFoundException e) {System.out.println ("No such class:" + E);
  }} class Stripqualifiers {private Streamtokenizer st;
      Public stripqualifiers (String qualified) {st = new Streamtokenizer (new StringReader (qualified)); St.ordinarychar (");
    Keep the spaces} public String GetNext () {string s = null; try {if (St.nexttoken ()!= streamtokenizer.tt_eof) {switch (st.ttype) {case Streamtok
            Enizer.tt_eol:s = null;
          Break
            Case streamtokenizer.tt_number:s = double.tostring (st.nval);
       Break   Case streamtokenizer.tt_word:s = new String (st.sval);
          Break
        Default://single character in ttype s = string.valueof ((char) st.ttype);
    catch (IOException e) {System.out.println (e);
  return s;
    public static string strip (String qualified) {stripqualifiers sq = new stripqualifiers (qualified);
    String s = "", si;
      while (si = Sq.getnext ())!= null) {int lastdot = Si.lastindexof ('. ');
      if (Lastdot!=-1) si = si.substring (lastdot + 1);
    s + + si;
  return s; }
} ///:~

The Showmethodsclean method is very close to the previous showmethods, but it obtains the methods and constructor arrays and converts them to a single string array. Each such string object is then "passed" in Stripqualifiers.strip (), removing all method qualifiers. As you can see, Streamtokenizer and string are used at this time to do this work.
The tool saves a lot of programming time if you don't remember whether a class has a specific method, and you don't want to step through the class structure in an online document, or whether that class can do something to an object, such as a color object.
The 17th chapter provides a GUI version of the program that you can run when you write code to quickly find what you need.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.