1. Trang chủ
  2. » Công Nghệ Thông Tin

java reflection in action, 2005

297 553 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 297
Dung lượng 1,71 MB

Nội dung

Ira R. Forman Nate Forman MANNING PRAISE FOR Java Reflection in Action Java Reflection in Action is unique in presenting a clear account of all the cool things you can do with reflection, and at the same time pro- viding the sound conceptual basis that developers need to create advanced applications. The book includes careful explanations of sometimes perplexing programming techniques along with enough background to understand how to extend and vary them. This book overcomes reflection’s reputation as a mysterious and esoteric philo- sophical pursuit, or as a set of messy error-prone coding tricks. As reflection becomes increasingly common and useful in all sorts of applications, it is great to finally have a book that features disci- plined yet still creative and fun software engineering practices based on reflection. Even occasional users will immediately adopt the book’s patterns and idioms to solve common problems. Many of the examples can be directly adapted for customized solutions in diverse areas such as XML processing, automated software testing, and pro- gram analysis tools. Readers will also find underlying rationales for code performing introspection, proxies, class loading, and so on, that are often seen but not often explained well in everyday Java pro- grams. And even experts will find new ideas and well-thought out advice for using some of the more subtle aspects of reflection. —Prof. Doug Lea, SUNY Oswego, author of Concurrent Programming in Java Java has brought reflection to the programming masses, but they're still struggling with it. The Formans turn struggle into adventure as they guide you through one compelling example after another, each one illustrating reflection’s power while avoiding its pitfalls. —Dr. John Vlissides, IBM —coauthor of Design Patterns Java Reflection in Action IRA R. FORMAN NATE FORMAN MANNING Greenwich (74° w. long.) For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. 209 Bruce Park Avenue Fax: (203) 661-9018 Greenwich, CT 06830 email: manning@manning.com ©2005 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books they publish printed on acid-free paper, and we exert our best efforts to that end. Manning Publications Co. Copyeditor: Linda Recktenwald 209 Bruce Park Avenue Typesetter: Dottie Marsico Greenwich, CT 06830 Cover designer: Leslie Haimes ISBN 1-932394-18-4 Printed in the United States of America 12345678910–VHG–07 060504 To Janet/Mom This project wouldn’t have happened without your love and support. vii contents preface xiii acknowledgments xv about this book xvii about the title xx about the cover illustration xxi 1 A few basics 1 1.1 Reflection’s value proposition 3 1.2 Enter George the programmer 4 Choosing reflection 5 ■ Programming a reflective solution 6 1.3 Examining running programs 8 1.4 Finding a method at runtime 10 1.5 Representing types with class objects 12 Representing primitive types 13 ■ Representing interfaces 13 Representing array types 14 1.6 Understanding method objects 14 Using dynamic invocation 15 ■ Using primitives with dynamic invocation 16 ■ Avoiding invocation pitfalls 17 1.7 Diagramming for reflection 19 viii CONTENTS 1.8 Navigating the inheritance hierarchy 20 Introspecting the inheritance hierarchy 22 ■ Exposing some surprises 23 ■ Another reflective circularity 24 1.9 Summary 26 2 Accessing fields reflectively 27 2.1 Serializing objects 28 Serializing to XML 29 ■ Choosing reflection 30 Designing serialization with reflection 30 2.2 Finding fields at runtime 31 2.3 Understanding field objects 33 2.4 Getting and setting field values 34 2.5 Examining modifiers 35 Introducing Member 36 ■ Interface introspection pitfall 37 Introspecting for instance variables 37 2.6 Accessing nonpublic members 38 2.7 Working with arrays 40 2.8 Serialization: putting it all together 41 Serializing each component 43 ■ Serializing instance variables 43 2.9 Using reflective serialization 45 2.10 Summary 48 3 Dynamic loading and reflective construction 49 3.1 George’s deployment problem 50 Designing with patterns 51 ■ Programming a reflective solution 52 Enhancing the factory method with reflection 54 ■ Combining benefits of delegation and reflection 54 3.2 Loading classes dynamically 55 Basics of forName 55 ■ Getting array classes 56 Primitives and forName 56 3.3 Constructing objects reflectively 57 Reflective construction basics 57 ■ Using constructor objects 57 Constructing arrays reflectively 59 3.4 Designing for dynamic loading 60 Disadvantages of reflective construction with arguments 61 Initializing through an interface 62 CONTENTS ix 3.5 Implementing deserialization 63 Initiating deserialization 64 ■ Constructing the instances 65 Restoring the object structure 66 3.6 George’s serialization: limitations 69 No interaction with readObject or writeObject 69 ■ No handling of final instance variables 70 ■ Only no-argument constructors 70 No handling of illegal XML characters 70 ■ Performance 71 3.7 Summary 71 4 Using Java’s dynamic proxy 73 4.1 Working with proxies 74 4.2 George’s tracing problem 76 4.3 Exploring Proxy 77 Understanding invocation handlers 79 Handling the methods of Object 80 4.4 Implementing a tracing proxy 81 4.5 A note on factories 84 4.6 Chaining proxies 86 Structuring invocation handlers for chaining 86 ■ Implementing a synchronized proxy 88 ■ Chaining the two proxies 89 4.7 Stubbing interfaces for unit testing 90 Examining stubs 90 ■ Design for stubbing with Proxy 91 Implementation of stubbing with Proxy 93 4.8 Generating SOAP remote proxies 99 4.9 Pitfalls of using Proxy 103 4.10 Summary 105 5 Call stack introspection 107 5.1 George’s logging problem 108 5.2 Performing call stack introspection 111 5.3 Logging with call stack introspection 112 5.4 Pitfalls 114 5.5 Class invariant checking 115 5.6 Summary 120 [...]... the structure of Java Think of introspection as looking at yourself in a mirror The mirror provides you with a representation of yourself—your reflection to examine Examining yourself in a mirror gives you all sorts of useful information, such as what shirt goes with your brown pants or whether you have something green stuck in your teeth That information can be invaluable in adjusting the structure... contribution to the AO remains voluntary (and unpaid) We suggest you try asking the authors some challenging questions lest their interest stray! about the title By combining introductions, overviews, and how-to examples, the In Action books are designed to help learning and remembering According to research in cognitive science, the things people remember are things they discover during self-motivated exploration... printing the returned name Without being overridden, the printName method behaves differently for each subclass than it does for HelloWorld The printName method is flexible; it adapts to the class that inherits it, causing the change in behavior As we build our examples in scope and complexity, we will show you many more ways to attain flexibility using reflection 1.1 Reflection s value proposition Reflection. .. reflective programming, which other production languages will influence the future of reflection in Java, and the influence of Aspect-Oriented Programming Appendix A is a reprise of the introduction to reflection but with a more academic point of view The appendix presents a brief history of reflection and the terminology that you are likely to encounter when reading advanced papers Appendix B explains how to... understanding of Java reflection by using it in the techniques It also motivates ideas about next-generation features, preparing you to use them This book is prescriptive That is, it advocates techniques for using Java reflection that we have used and profited from in our jobs Source code The examples in this book have all been compiled and minimally tested Source code examples are available online from... Putting Metaclasses to Work, which was published in 1999 About that time, Ira’s son Nate was looking for a topic for a master’s paper at the University of Texas at Austin Nate accepted Ira’s suggestion: study the use of reflection to support the application of Gang-of-Four2 design patterns The resulting paper led to some interesting insights into both reflection and patterns But most of all, it reinforced... standard out Now let x be an instance of HelloWorld or one of its subclasses The line x.printName(); sends the string naming the class to standard out This small example is more dramatic than it seems—it contains each of the steps previously mentioned The printName method examines the object for its class (this.getClass()) In doing so, the decision of what to print is made by delegating to the object’s class... teachable examples, mainly in the area of software development and test tools, a problem area common to all programmers We describe the reflective facilities and also prescribe effective ways to use them Convey an understanding of reflection in general Reflection is much broader than what is incorporated in Java We discuss the limitations of Java reflection and show techniques for working around them This... component’s color without knowing its concrete type The method accomplishes its goals without invading the source code of any of the components It also avoids source code bloating, memory bloating, and unnecessary coupling George has implemented an extremely flexible and effective solution Two lines in listing 1.1 use reflection to examine the structure of the parameter obj: b C This line of code queries the... programming has moved to C# versus Java Control of an architecture is where the big money is made in information technology In the 1980s, IBM ceded control over the hardware architecture of personal computers to Intel; as a result, today we speak about “Intel inside” and not “IBM compatible.” For more information about the importance of controlling an architecture, see Computer Wars: How the West Can Win in . Forman MANNING PRAISE FOR Java Reflection in Action Java Reflection in Action is unique in presenting a clear account of all the cool things you can do with reflection, . Implementing a tracing proxy 81 4.5 A note on factories 84 4.6 Chaining proxies 86 Structuring invocation handlers for chaining 86 ■ Implementing a synchronized

Ngày đăng: 20/03/2014, 15:40

TỪ KHÓA LIÊN QUAN