LET'S CONNECT!
Enter for a chance to win an eBook of your choice from InformIT. Fill out the form.
Register your product to gain access to bonus material or receive a coupon.
If you're serious about writing components in Java, this book focuses on the component services you need to master. DevelopMentor Chief Scientist Stuart Halloway presents unprecedented, in-depth coverage of writing, deploying, and maintaining Java components. Halloway begins by showing how to use, control, and troubleshoot components. He offers real-world guidance on reflection performance, and demonstrates how reflection is used to build the Java serialization architecture. He also offers detailed coverage of using the Java Native Interface (JNI) to control the boundaries between Java code and components written in other environments. In Part II, Halloway presents a practical vision for using component services to become a more effective Java developer. Through examples and sample code, he introduces generative programming techniques that leverage Java into high performance. Finally, building on these techniques, he shows how to construct robust interoperability between Java and Win32/COM.
Java Type Information and Reflection
Click below for Sample Chapter related to this title:
hallowaych03.pdf
Preface.
1. From Objects to Components.
2. The Class Loader Architecture.
Assembling an Application.
Goals of the Class Loader Architecture.
Transparency.
Extensibility.
Capability @
Configurability.
Handling Name and Version Conflicts.
Security.
Explicit and Implicit Class Loading.
Explicit Loading with URLClassLoader.
Implicit Class Loading.
Reference Type vs. Referenced Class.
ClassLoader.loadClass vs. Class.forName.
Loading Nonclass Resources.
The Class Loader Rules.
The Consistency Rule.
The Delegation Rule.
The Visibility Rule.
Delegations as Namespaces.
Static Fields are Not Singletons.
Implicit Loading Hides Most Details.
Hot Deployment.
Using Hot Deployment.
Unloading Classes.
Making Sure Classes are Collectable.
Bootclasspath, Extensions Path, and Classpath.
The Classpath.
The Extensions Path.
The Bootstrap Loader.
Debugging Class Loading.
Instrumenting an Application.
Using -verbose:class.
Instrumenting the Core API.
Inversion and the Context Class Loader.
Onward.
Resources.
The Binary Class Format.
Binary Compatibility.
Binary Class Metadata.
From Binary Classes to Reflection.
Reflection.
Reflecting on Fields.
The Difference between get and getDeclared.
Type Errors Occur at Runtime.
Reflecting on Methods.
Reflective Invocation.
A Reflective Launcher.
Wrapping Primitive Types.
Bypassing Language Access Rules.
Exceptions Caused by Reflective Invocation.
Dynamic Proxies.
Delegation Instead of Implementation Inheritance.
Dynamic Proxies Make Delegation Generic.
Implementing InvocationHandler.
Implementing a Forwarding Handler.
The InvocationHandler as Generic Service.
Handling Exceptions in an InvocationHandler.
Either Client or Server can Install a Proxy.
Advantages of Dynamic Proxies.
Reflection Performance.
Package Reflection.
Setting Package Metadata.
Accessing Package Metadata.
Sealing Packages.
Weaknesses of the Versioning Mechanism.
Custom Metadata.
Onward.
Resources.
Serialization and Metadata.
Serialization Basics.
Serialization Skips Some Fields.
Serialization And Class Constructors.
Using readObject and writeObject.
Matching Streams With Classes.
The serialVersionUID.
Overriding the Default SUID.
Compatible and Incompatible Changes.
Explicitly Managing Serializable Fields.
ObjectInputStream.GetField Caveats.
Writer Makes Right.
Overriding Class Metadata.
Performance Problems.
Custom Class Descriptors.
Abandoning Metadata.
Writing Custom Data After defaultWriteObject.
Externalizable.
Using writeObject to Write Raw Data Only: Bad Idea.
Object Graphs.
Pruning Graphs with Transient.
Preserving Identity.
Encouraging the Garbage Collector with Reset.
Object Replacement.
Stream-Controlled Replacement.
Class-Controlled Replacement.
Ordering Rules for Replacement.
Taking Control of Graph Ordering.
Finding Class Code.
Annotation in RMI.
RMI MarshalledObjects.
Onward.
Resources.
Java 2 Security.
The Role of Class Loaders.
Custom Class Loaders.
Pre-Java 2 Custom Class Loaders.
Class Loading Since SDK 1.2.
A Transforming Class Loader.
Protocol Handlers.
Implementing a Handler.
Installing a Custom Handler.
Choosing Between Loaders and Handlers.
Getting Past Security to the Loader You Need.
Reading Custom Metadata.
Example: Version Attributes.
Serializable Classes as Attributes.
Reading Attributes During Class Loading.
Debugging Support.
Onward.
Resources.
Why Interoperate?
The Dangers of Native Code.
Finding and Loading Native Code.
Name Mappings.
Type Mappings.
Overloaded Names.
Loading Native Libraries.
Class Loaders and JNI.
Common Errors Loading Native Libraries.
Troubleshooting Native Loading.
Calling Java from C++.
Minimizing Round Trips.
Performance Comparisons.
Differences Between JNI and Reflective Invocation.
Error Handling in JNI.
Failures in Native Code.
Handling C++ Exceptions.
Handling Java Exceptions from Native Code.
Throwing Java Exceptions from Native Code.
Resource Management.
Interacting with the Garbage Collector.
Managing Native Resources.
Managing Arrays.
Managing Strings.
Onward.
Resources.
Why Generate Code?
Object Oriented Approaches to Modeling Variabilities.
Thinking in Terms of Bind Time.
Separating Specification From Bind Time.
Choosing a Specification Language.
Reuse Requires More than One Use.
A Little Domain Analysis is a Dangerous Thing.
Why Generate Code with Java?
Type Information Acts As a Free Specification Document.
Class Loading Supports Flexible Binding Modes.
Java Source is Easy To Generate.
Java Binary Classes are Easy To Generate.
Code Generation Boosts Performance.
Levels of Commitment to Code Generation.
A Taxonomy of Bind Times and Modes.
Code Generation in RMI.
Code Generation in JSP.
Code Generation in EJB.
The Deployment Descriptor.
Alternate Implementations.
Generating Strongly Typed Collections.
Code Generation Language versus Target Language.
Generating Custom Serialization Code.
Onward.
Resources.
Where We Are.
Where We Are Going.
Resources.
This book is about developing components using the Java platform. In this book, the term component has a very specific meaning. A component is an independent unit of production and deployment that is combined with other components to assemble an application.
To elaborate on this definition, consider the difference between objects and components. An object represents an entity in the problem domain, while a component is an atomic piece of the installed solution. The object and component perspectives are complementary, and good designs take account of both.
Modern development platforms such as Java provide the infrastructure that developers need to create classes and components. To support object-oriented programming, Java provides encapsulation, inheritance, and polymorphism. To support components, Java provides loaders and rich type information. This book assumes that you already understand object-oriented programming in Java, and it explains how to use Java's component infrastructure effectively.
Loaders are responsible for locating, bringing into memory, and connecting components at runtime. Using Java's loaders, you can
Loaders manage the binary boundaries between components. In a world of distributed applications and multiple component suppliers, loaders locate and connect compatible components.
Type information describes the capabilities of some unit of code. In some development environments type information is present only in source code. In Java, type information is not merely a source code artifact; it is also an intrinsic part of a compiled class and is available at runtime through a programmatic interface. Because Java type information is never "compiled away," loaders use it to verify linkages between classes at runtime. In application programming, you can use type information to
You should read this book if you want to design, develop, or deploy substantial applications in Java. Taking a full-lifecycle view of a Java application requires that you consider not just objects, but components. This book is about the core features of Java as a component platform: class loaders, reflection, serialization, and interoperation with other platforms. You should already know the basics of Java syntax and have some experience in object-oriented programming with Java.
This book is not specifically about high-level Java technologies, such as Remote Method Invocation (RMI), Enterprise JavaBeans (EJB), JINI, Java Server Pages (JSP), servlets, or JavaBeans, but understanding the topics in this book is critical to using those technologies effectively. If you learn how to use the component services described here, you will understand how these high-level technologies are built, which is the key to employing them effectively.
Security is also an important aspect of component development and deployment. It is too complex a topic to handle fairly here, and it deserves its own book-length treatment. (See Gon99 for coverage of security on the Java platform.)
The chapters of this book fall into three sections. Chapter 1 introduces components. Chapters 2 through 6 explain loaders and type information on the Java platform. Chapter 7 shows more advanced uses of these services.
Chapter 1 introduces component-oriented programming. Component relationships must be established not only at compile time, but also at deployment and runtime. This chapter asks the key questions of component programming and relates them to the Java platform services discussed in subsequent chapters. Though the other chapters might be read out of order, you should definitely read this chapter first.
Chapter 2 shows how to use and troubleshoot class loaders. Class loaders control the loading of code and create namespace boundaries between code in the same process. With class loaders you can load code dynamically at runtime, even from other machines. Class loader namespaces permit multiple versions of the same class in a single Java virtual machine. You can use class loaders to reload changed classes without ever shutting down the virtual machine. You will see how to use class loaders, how the class loader delegation model creates namespaces, and how to troubleshoot class loading bugs. You will also learn to effectively control the bootclasspath, extensions path, and classpath.
Chapter 3 introduces Java type information. Java preserves type information in the binary class format. This means that even after you compile your Java programs, you still have access to field names, field types, and method signatures. You can access type information at runtime via reflection, and you can use type information to build generic services that add capability to any object. You will see how to use dynamic invocation, dynamic proxies, package reflection, and custom attributes. Chapter 3 also includes a discussion of reflection performance.
Chapter 4 shows how Java serialization uses reflection. Serialization is a perfect example of a generic service. Without any advance knowledge of a class's layout, serialization can ship both code and state from one virtual machine to another across time or space. You will see how the serialization format embeds its own style of type information and how you can customize that representation. You will also see how to extend default serialization, replace it entirely with custom externalization code, or tune it to handle multiple versions of a class as code evolves. You will then learn how to validate objects being deserialized into your application and how to annotate serialized objects with instructions for finding the correct class loader.
Chapter 5 returns to class loaders and shows you how to implement your own. While the standard class loaders are dominant in most applications, custom class loaders allow you to transform class code as classes are loaded. These transformations could include decryption, adding instrumentation for performance monitoring, or even building new classes on-the-fly at runtime. You will see how to tie your custom class loaders into Java's security architecture, how to write a custom class loader, and how to write protocol handlers that can customize not just how you load classes, but also how you load any other type of resource.
Chapter 6 presents the Java Native Interface (JNI) as a basic means of controlling the boundary between Java code and components written in other environments. JNI provides a set of low-level tools for exposing Java objects to platform native code and native code to Java objects. You will learn to use the JNI application programming interface (API) to translate between Java and native programming styles—which differ markedly in their approach to class loading, type information, resource management, error handling, and array storage. Understanding the deficiencies of JNI sets the stage for Appendix A, which describes a higher-level approach.
Chapter 7 discusses using Java metadata to automate the creation of source code or bytecode. Generated code is a high-performance strategy for reuse because you generate only the exact code paths that you will need at runtime. The chapter first presents JSP and EJB as examples of existing applications that auto-generate code, and then it introduces some ideas for code generation in your own programs.
Appendix A returns to interoperation. By building on the code generation techniques from Chapter 7, Appendix A shows you how to build an interoperation layer between Java and another component platform: Win32/COM. This chapter uses the open source Jawin library as an example, to show you how to generate Java stubs for Win32 objects, and vice versa.
Unless specifically noted otherwise, all the sample code in this book is open source. You can download sample code from the book's website at http://staff.develop.com/halloway/compsvcs.html.
Unless otherwise noted, the code in this book is compiled and tested against the Java 2 Software Development Kit (SDK) version 1.3. Most of the code in the book will work identically under SDK versions 1.2, 1.3, and 1.4. Where this is not the case, the text will include a specific reference to the appropriate SDK version.
The author welcomes your comments, corrections, and feedback. Please send email to stu@develop.com.
Download the Bibliography related to this title.
Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.
This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.
To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:
For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.
For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.
Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.
Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.
If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.
On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.
We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.
Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.
Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.
This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.
This site currently does not respond to Do Not Track signals.
Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.
This site is not directed to children under the age of 13.
Pearson may send or direct marketing communications to users, provided that
Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.
If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.
Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.
Pearson does not rent or sell personal information in exchange for any payment of money.
While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.
California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.
Pearson may disclose personal information, as follows:
This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.
Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.
We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.
Last Update: November 17, 2020