面向对象技术及语言-第10章_第1页
面向对象技术及语言-第10章_第2页
面向对象技术及语言-第10章_第3页
面向对象技术及语言-第10章_第4页
面向对象技术及语言-第10章_第5页
已阅读5页,还剩40页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、面向对象技术及语言面向对象技术及语言 Object-Oriented Technology & LanguageObject-Oriented Technology & Language 主讲教师: 饶若楠上海交通大学计算机科学与工程系rao- 2 第第12章章 Detecting Types 12.1 The need for RTTI 12.2 RTTI syntax 12.3 Reflection 3 12.1 The Need for RTTI Problem: How to discover information about objects and classes at run-t

2、ime? Approach: 1) “traditional” RTTI, which assumes that you have all the types available at compile-time and run-time 2) the “reflection” mechanism, which allows you to discover class information solely at run-time. 4 12.1 The Need for RTTI Review polymorphism 5 12.1 The Need for RTTI Review polymo

3、rphismimport java.util.*; class Shape void draw() System.out.println(this + .draw(); class Circle extends Shape public String toString() return Circle; class Square extends Shape public String toString() return Square; class Triangle extends Shape public String toString() return Triangle; 6 12.1 The

4、 Need for RTTI Review polymorphismpublic class Shapes public static void main(String args) ArrayList s = new ArrayList(); s.add(new Circle(); s.add(new Square(); s.add(new Triangle(); Iterator e = s.iterator(); while(e.hasNext() (Shape)e.next().draw(); 7 12.1 The Need for RTTI Class ObjectJava RTTI:

5、 how type information is represented at run-time ? This is accomplished through a special kind of object called the Class object, which contains information about the class. Each time you write and compile a new class, a single Class object is also created (and stored, appropriately enough, in an id

6、entically named .class file). At run-time, when you want to make an object of that class, the Java Virtual Machine (JVM) thats executing your program first checks to see if the Class object for that type is loaded. If not, the JVM loads it by finding the .class file with that name. Once the Class ob

7、ject for that type is in memory, it is used to create all objects of that type 8 12.1 The Need for RTTI Class Object/: c12:SweetShop.javaclass Candy static System.out.println(Loading Candy); class Gum static System.out.println(Loading Gum); class Cookie static System.out.println(Loading Cookie); pub

8、lic class SweetShop public static void main(String args) System.out.println(inside main); new Candy(); System.out.println(After creating Candy); try Class.forName(Gum); catch(ClassNotFoundException e) e.printStackTrace(System.err); System.out.println( After Class.forName(Gum); new Cookie(); System.o

9、ut.println(After creating Cookie); 9 12.1 The Need for RTTI java.lang.Class public final class Class extends Object implements Serializable Instances of the class Class represent classes and interfaces in a running Java application. Class has no public constructor. Instead Class objects are construc

10、ted automatically by the JVM as classes are loaded and by calls to the defineClass method in the class loader. Note: Every class has Object as a superclass. Object has a method getClass(): public final Class getClass() This method returns the runtime class of an object. That Class object is the obje

11、ct that is locked by static synchronized methods of the represented class. 10 12.1 The Need for RTTI reference to the Class ObjectThere are two ways to get a reference to the Class object: 1) public static Class forName(String className) throws ClassNotFoundException Returns the Class object associa

12、ted with the class or interface with the given string name.Or public static Class forName(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException Class.forName(“Gum”) is equivalent to: Class.forName(“Gum, true, this.getClass().getClassLoader() 2) Class literals Java provid

13、es a second way to produce the reference to the Class object, using a class literal. In the above program this would look like: Gum.class; 11 12.1 The Need for RTTI three RTTI forms (p478-485)1)The classic cast; e.g., “(Shape),” which uses RTTI to make sure the cast is correct and throws a ClassCast

14、Exception if youve performed a bad cast. 2)The Class object representing the type of your object. The Class object can be queried for useful run-time information. 3) the keyword instanceof that tells you if an object is an instance of a particular type. It returns a boolean so you use it in the form

15、 of a question, like this: if(x instanceof Dog) (Dog)x).bark(); 12 12.1 The Need for RTTI three RTTI forms (p478-485)Note: The Class isInstance method provides a way to dynamically call the instanceof operator. public boolean isInstance(Object obj) Determines if the specified Object is assignment-co

16、mpatible with the object represented by this Class. 13 12.2 RTTI syntax Java performs its RTTI using the Class object, even if youre doing something like a cast. The class Class also has a number of other ways you can use RTTI. First, you must get a reference to the appropriate Class object.( One wa

17、y to do thisis to use a string and the Class.forName( ) method. However, if you do already have an object of the type youre interested in, you can fetch the Class reference by calling a method thats part of the Object root class: getClass( ). This returns the Class reference representing the actual

18、type of the object.) Class has many interesting methods, demonstrated in the following example: ToyTest.java 14 12.2 RTTI syntax java.lang.Class (1) 15 12.2 RTTI syntax java.lang.Class (2) 16 12.2 RTTI syntax ToyTest.java Example (p485-486)class FancyToy extends Toy implements HasBatteries, Waterpro

19、of, ShootsThings Class c = null; c = Class.forName(FancyToy); Class faces = c.getInterfaces();Class cy = c.getSuperclass(); Object o = null; o = cy.newInstance(); printInfo(o.getClass();static void printInfo(Class cc) System.out.println( Class name: + cc.getName() + is interface? + cc.isInterface()

20、+ ); 17 12.3 Reflection: run-time class information A limitation of RTTI: 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. In other words, the compiler must know about all the classes youre working with for RTTI.

21、 Problem: How to get run-time class information? Reflection provides the mechanism to get the information of a class whose name is not known until runtime. Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields,

22、methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class. 18 12.3 Reflection

23、: run-time class information The reflection API represents, or reflects, the classes, interfaces, and objects in the current Java Virtual Machine. Youll rarely need to use the reflection tools directly; theyre in the language to support other Java features, such as object serialization (Chapter 11),

24、 JavaBeans (Chapter 13), and RMI (Chapter 15). However, there are times when its quite useful to be able to dynamically extract information about a class. 19 12.3 Reflection: run-time class information With the reflection API you can: Determine the class of an object. Get information about a classs

25、modifiers, fields, methods, constructors, and superclasses. Find out what constants and method declarations belong to an interface. Create an instance of a class whose name is not known until runtime. Get and set the value of an objects field, even if the field name is unknown to your program until

26、runtime. Invoke a method on an object, even if the method is not known until runtime. Create a new array, whose size and component type are not known until runtime, and then modify the arrays components. 20 12.3 Reflection - Applications The Core Reflection API accommodates two categories of applica

27、tions. One category is comprised of applications that need to discover and use all of the public members of a target object based on its run-time class. These applications require run-time access to all the public fields, methods, and constructors of an object. Examples in this category are services

28、 such as JavaBeans, and lightweight tools, such as object inspectors. These applications use the instances of the classes Field, Method, and Constructor obtained through the methods getField, getMethod, getConstructor, getFields, getMethods, and getConstructors of class Class. The second category co

29、nsists of sophisticated applications that need to discover and use the members declared by a given class. These applications need run-time access to the implementation of a class at the level provided by a class file. Examples in this category are development tools, such as interpreters, inspectors,

30、 and class browsers, and run-time services, such as Java Object Serialization. These applications use instances of the classes Field, Method, and Constructor obtained through the methods getDeclaredField, getDeclaredMethod, getDeclaredConstructor, getDeclaredFields, getDeclaredMethods, and getDeclar

31、edConstructors of class Class. 21 12.3 Reflection API Overview The Class and Object classes are in the java.lang package. The other classes are contained in the java.lang.reflect package. ClassDescriptionArrayProvides static methods to dynamically create and access arrays. ClassRepresents, or reflec

32、ts, classes and interfaces. ConstructorProvides information about, and access to, a constructor for a class. Allows you to instantiate a class dynamically. FieldProvides information about, and dynamic access to, a field of a class or an interface. MethodProvides information about, and access to, a s

33、ingle method on a class or interface. Allows you to invoke the method dynamically. ModifierProvides static methods and constants that allow you to get information about the access modifiers of a class and its members. ObjectProvides the getClass method. 22 12.3 Reflection java.lang.reflect.* MethodM

34、emberFieldAccessibleObjectArrayConstructorInvocationHandlerInvocationTargetExceptionModifierProxyReflectPermissionUndeclaredThrowableExceptionSuppressing Reflective Access ControlReflection Modeldynamic proxy class 23 12.3 Reflection Reflection Model The three classes Field, Method, and Constructor

35、are final. Only the Java Virtual Machine may create instances of these classes; these objects are used to manipulate the underlying objects; that is, to: get reflective information about the underlying member or constructorget and set field valuesinvoke methods on objects or classescreate new instan

36、ces of classesThe final uninstantiable class Array provides static methods that permit creating new arrays, and getting and setting the elements of arrays. 24 12.3 Reflection Model java.lang.reflect.Memberpackage java.lang.reflect;public interface Member public static final int PUBLIC = 0; public st

37、atic final int DECLARED = 1; public Class getDeclaringClass(); public String getName(); public int getModifiers();The classes Field, Method and Constructor implement the Member interface. The methods of Member are used to query a reflected member for basic identifying information. Identifying inform

38、ation consists of the class or interface that declared the member, the name of the member itself, and the Java language modifiers (such as public, protected, abstract, synchronized, and so on) for the member. 25 12.3 Reflection Model java.lang.reflect.Fieldpublic final class Field extends Accessible

39、Object implements Member A Field object represents a reflected field. The underlying field may be a class variable (a static field) or an instance variable (a non-static field). Methods of class Field are used to obtain the type of the underlying field, and to get and set the underlying fields value

40、 on objects. 26 12.3 Example - Identifying Class Fields import java.lang.reflect.*; import java.awt.*; class SampleField public static void main(String args) GridBagConstraints g = new GridBagConstraints(); printFieldNames(g); static void printFieldNames(Object o) Class c = o.getClass(); Field publi

41、cFields = c.getFields(); for (int i = 0; i publicFields.length; i+) String fieldName = publicFieldsi.getName(); Class typeClass = publicFieldsi.getType(); String fieldType = typeClass.getName(); System.out.println(Name: + fieldName + , Type: + fieldType); 27 12.3 Example - Setting Field Values impor

42、t java.lang.reflect.*; import java.awt.*; class SampleSet public static void main(String args) Rectangle r = new Rectangle(100, 20); System.out.println(original: + r.toString(); modifyWidth(r, new Integer(300); System.out.println(modified: + r.toString(); static void modifyWidth(Rectangle r, Integer

43、 widthParam ) Field widthField; Integer widthValue; Class c = r.getClass(); try widthField = c.getField(width); widthField.set(r, widthParam); catch (NoSuchFieldException e) System.out.println(e); catch (IllegalAccessException e) System.out.println(e); 28 12.3 Reflection Model java.lang.reflect.Meth

44、odpublic final class Method extends AccessibleObject implements Member A Method object represents a reflected method. The underlying method may be an abstract method, an instance method, or a class (static) method. Methods of class Method are used to obtain the formal parameter types, the return typ

45、e, and the checked exception types of the underlying method. In addition, the invoke method of class Method is used to invoke the underlying method on target objects. Instance and abstract method invocation uses dynamic method resolution based on the target objects run-time class and the reflected m

46、ethods declaring class, name, and formal parameter types. Static method invocation uses the underlying static method of the methods declaring class. 29 12.3 Example - Obtaining Method Information import java.lang.reflect.*; import java.awt.*; class SampleMethod public static void main(String args) P

47、olygon p = new Polygon(); showMethods(p); static void showMethods(Object o) Class c = o.getClass(); Method theMethods = c.getMethods(); for (int i = 0; i theMethods.length; i+) String methodString = theMethodsi.getName(); System.out.println(Name: + methodString); String returnString = theMethodsi.ge

48、tReturnType().getName(); System.out.println( Return Type: + returnString); Class parameterTypes = theMethodsi.getParameterTypes(); System.out.print( Parameter Types:); for (int k = 0; k parameterTypes.length; k +) String parameterString = parameterTypesk.getName(); System.out.print( + parameterStrin

49、g); System.out.println(); 30 12.3 Example - Invoking Methods import java.lang.reflect.*;class SampleInvoke public static void main(String args) String firstWord = Hello ; String secondWord = everybody.; String bothWords = append(firstWord, secondWord); System.out.println(bothWords); public static St

50、ring append(String firstWord, String secondWord) String result = null; Class c = String.class; Class parameterTypes = new Class String.class; Method concatMethod; Object arguments = new Object secondWord; try concatMethod = c.getMethod(concat, parameterTypes); result = (String) concatMethod.invoke(f

51、irstWord, arguments); catch (NoSuchMethodException e) System.out.println(e); catch (IllegalAccessException e) System.out.println(e); catch (InvocationTargetException e) System.out.println(e); return result; 31 12.3 Reflection Model java.lang.reflect.Constructorpublic final class Constructor extends

52、AccessibleObject implements Member A Constructor object represents a reflected constructor. Methods of class Constructor are used to obtain the formal parameter types and the checked exception types of the underlying constructor. In addition, the newInstance method of class Constructor is used to cr

53、eate and initialize a new instance of the class that declares the constructor, provided the class is instantiable. 32 12.3 Example - Discovering Class Constructors import java.lang.reflect.*;import java.awt.*; class SampleConstructor public static void main(String args) Rectangle r = new Rectangle()

54、; showConstructors(r); static void showConstructors(Object o) Class c = o.getClass(); Constructor theConstructors = c.getConstructors(); for (int i = 0; i theConstructors.length; i+) System.out.print( ); Class parameterTypes = theConstructorsi.getParameterTypes(); for (int k = 0; k parameterTypes.le

55、ngth; k +) String parameterString = parameterTypesk.getName(); System.out.print(parameterString + ); System.out.println(); 33 12.3 Example - Using Constructors that Have Arguments import java.lang.reflect.*; import java.awt.*; class SampleInstance public static void main(String args) Rectangle recta

56、ngle; Class rectangleDefinition; Class intArgsClass = new Class int.class, int.class; Integer height = new Integer(12); Integer width = new Integer(34); Object intArgs = new Object height, width; Constructor intArgsConstructor; try rectangleDefinition = Class.forName(java.awt.Rectangle); intArgsCons

57、tructor = rectangleDefinition.getConstructor(intArgsClass); rectangle = (Rectangle) createObject(intArgsConstructor, intArgs); catch (ClassNotFoundException e) System.out.println(e); catch (NoSuchMethodException e) System.out.println(e); public static Object createObject(Constructor constructor, Obj

58、ect arguments) System.out.println (Constructor: + constructor.toString(); Object object = null; try object = constructor.newInstance(arguments); System.out.println (Object: + object.toString(); return object; catch (InstantiationException e) System.out.println(e); catch (IllegalAccessException e) Sy

59、stem.out.println(e); catch (IllegalArgumentException e) System.out.println(e); catch (InvocationTargetException e) System.out.println(e); return object; 34 12.3 Reflection Model java.lang.reflect.Modifierpublic class Modifier extends Object The Modifier class provides static methods and constants to

60、 decode class and member access modifiers. The sets of modifiers are represented as integers with distinct bit positions representing different modifiers. The values for the constants representing the modifiers are taken from “The Java Virtual Machine Specification. “ 35 12.3 Example - Discovering C

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论