Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  


AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Reflection: run-time class information

java

+ Font mai mare | - Font mai mic



DOCUMENTE SIMILARE

Trimite pe Messenger
Comments and embedded documentation
Calling constructors from constructors
Text fields
Using Sets
Overriding vs
Capturing an event
Connecting Java to CGI
Overloading on return values
You must create all the objects
private: you canít touch that


Reflection: run-time
class information

If you donít know the precise type of an object, RTTI will tell you. However, thereís a limitation: the type must be known at compile time in order for you to be able to detect it using RTTI and do something useful with the information. Put another way, the compiler must know about all the classes youíre working with for RTTI.




This doesnít seem like that much of a limitation at first, but suppose youíre given a handle to an object thatís not in your program space. In fact, the class of the object isnít even available to your program at compile time. For example, suppose you get a bunch of bytes from a disk file or from a network connection and youíre told that those bytes represent a class. Since the compiler canít know about the class while itís compiling the code, how can you possibly use such a class?

In a traditional programming environment this seems like a far-fetched scenario. But as we move into a larger programming world there are important cases in which this happens. The first is component-based programming in which you build projects using Rapid Application Development (RAD) in an application builder tool. This is a visual approach to creating a program (which you see on the screen as a form) by moving icons that represent components onto the form. These components are then configured by setting some of their values at program time. This design-time configuration requires that any component be instantiable and that it expose some part of itself and allow its values to be read and set. In addition, components that handle GUI events must expose information about appropriate methods so that the RAD environment can assist the programmer in overriding these event-handling methods. Reflection provides the mechanism to detect the available methods and produce the method names. Java 1.1 provides a structure for component-based programming through Java Beans (described in Chapter 13).

Another compelling motivation for discovering class information at run-time is to provide the ability to create and execute objects on remote platforms across a network. This is called Remote Method Invocation (RMI≠) and it allows a Java program (version 1.1 and higher) to have objects distributed across many machines. This distribution can happen for a number of reasons: perhaps youíre doing a computation-intensive task and you want to break it up and put pieces on machines that are idle in order to speed things up. In some situations you might want to place code that handles particular types of tasks (e.g. ďBusiness RulesĒ in a multi-tier client/server architecture) on a particular machine so that machine becomes a common repository describing those actions and it can be easily changed to affect everyone in the system. (This is an interesting development since the machine exists solely to make software changes easy!) Along these lines, distributed computing also supports specialized hardware that might be good at a particular task Ė matrix inversions, for example Ė but inappropriate or too expensive for general purpose programming.

In Java 1.1, the class Class (described previously in this chapter) is extended to support the concept of reflection, and thereís an additional library, java.lang.reflect, with classes Field, Method, and Constructor (each of which implement the Member interface). Objects of these types are created by the JVM at run-time to represent the corresponding member in the unknown class. You can then use the Constructors to create new objects, the get( ) and set( ) methods to read and modify the fields associated with Field objects, and the invoke( ) method to call a method associated with a Method object. In addition, you can call the convenience methods getFields( ), getMethods( ), getConstructors( ), etc., to return arrays of the objects representing the fields, methods, and constructors. (You can find out more by looking up the class Class in your online documentation.) Thus, the class information for anonymous objects can be completely determined at run time, and nothing need be known at compile time.

Itís important to realize that thereís nothing magic about reflection. When youíre using reflection to interact with an object of an unknown type, the JVM will simply look at the object and see that it belongs to a particular class (just like ordinary RTTI) but then, before it can do anything else, the Class object must be loaded. Thus, the .class file for that particular type must still be available to the JVM, either on the local machine or across the network. So the true difference between RTTI and reflection is that with RTTI, the compiler opens and examines the .class file at compile time. Put another way, you can call all the methods of an object in the ďnormalĒ way. With reflection, the .class file is unavailable at compile time; it is opened and examined by the run-time environment.

A class method extractor

Youíll rarely need to use the reflection tools directly; theyíre in the language to support the other Java features such as object serialization (described in Chapter 10), Java Beans, and RMI (described later in the book). However, there are times when itís quite useful to be able to dynamically extract information about a class. One extremely useful tool is a class method extractor. As mentioned before, looking at a class definition source code or online documentation shows only the methods that are defined or overridden within that class definition. But there could be dozens more available to you that have come from base classes. To locate these is both tedious and time consuming. Fortunately, reflection provides a way to write a simple tool that will automatically show you the entire interface. Hereís the way it works:

//: ShowMethods.java

// Using Java 1.1 reflection to show all the

// methods of a class, even if the methods are

// defined in the base class.

import java.lang.reflect.*;

public class ShowMethods

try

else

} catch (ClassNotFoundException e)

}

} ///:~

The Class methods getMethods( ) and getConstructors( ) return an array of Method and Constructor, respectively. Each of these classes has further methods to dissect the names, arguments, and return values of the methods they represent. But you can also just use toString( ), as is done here, to produce a String with the entire method signature. The rest of the code is just for extracting command line information, determining if a particular signature matches with your target string (using indexOf( )), and printing the results.



This shows reflection in action, since the result produced by Class.forName( ) cannot be known at compile-time, and therefore all the method signature information is being extracted at run-time. If you investigate your online documentation on reflection, youíll see that there is enough support to actually set up and make a method call on an object thatís totally unknown at compile-time. Again, this is something youíll probably never need to do yourself Ė the support is there for Java and so a programming environment can manipulate Java Beans Ė but itís interesting.

An interesting experiment is to run java ShowMethods ShowMethods. This produces a listing that includes a public default constructor, even though you can see from the code that no constructor was defined. The constructor you see is the one thatís automatically synthesized by the compiler. If you then make ShowMethods a non-public class (that is, friendly), the synthesized default constructor no longer shows up in the output. The synthesized default constructor is automatically given the same access as the class.

The output for ShowMethods is still a little tedious. For example, hereís a portion of the output produced by invoking 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)

It would be even nicer if the qualifiers like java.lang could be stripped off. The StreamTokenizer class introduced in the previous chapter can help solve this problem:

//: ShowMethodsClean.java

// ShowMethods with the qualifiers stripped

// to make the results easier to read

import java.lang.reflect.*;

import java.io.*;

public class ShowMethodsClean

try

for(int i = 0; i < ctor.length; i++)

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)

}

}

class StripQualifiers

public String getNext()

}

} catch(IOException e)

return s;

}

public static String strip(String qualified)

return s;

}

} ///:~

The class ShowMethodsClean is quite similar to the previous ShowMethods, except that it takes the arrays of Method and Constructor and converts them into a single array of String. Each of these String objects is then passed through StripQualifiers.Strip( ) to remove all the method qualification. As you can see, this uses the StreamTokenizer and String manipulation to do its work.

This tool can be a real time-saver while youíre programming, when you canít remember if a class has a particular method and you donít want to go walking through the class hierarchy in the online documentation, or if you donít know whether that class can do anything with, for example, Color objects.

Chapter 17 contains a GUI version of this program so you can leave it running while youíre writing code, to allow quick lookups.






Politica de confidentialitate



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 501
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2021 . All rights reserved

Distribuie URL

Adauga cod HTML in site