版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、面向?qū)ο蠹夹g(shù)及語言面向?qū)ο蠹夹g(shù)及語言 Object-Oriented Technology & LanguageObject-Oriented Technology & Language 主講教師: 饒若楠上海交通大學(xué)計(jì)算機(jī)科學(xué)與工程系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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 車輛工程課程設(shè)計(jì)懸架
- 銑槽課程設(shè)計(jì)前言
- 鐵路物流課程設(shè)計(jì)
- 誤差課程設(shè)計(jì)
- 飲水機(jī)課程設(shè)計(jì)
- 運(yùn)動區(qū)域探索課程設(shè)計(jì)
- 療愈師課課程設(shè)計(jì)
- 財(cái)務(wù)整合課程設(shè)計(jì)題
- 齒輪坯的課程設(shè)計(jì)
- 音樂思政課特色課程設(shè)計(jì)
- 英語-遼寧省大連市2024-2025學(xué)年高三上學(xué)期期末雙基測試卷及答案
- 2024年意識形態(tài)風(fēng)險(xiǎn)隱患點(diǎn)及應(yīng)對措施
- 2025版新能源充電樁加盟代理合作協(xié)議范本3篇
- 2025年廣東省揭陽市揭西縣招聘事業(yè)單位人員11人歷年高頻重點(diǎn)提升(共500題)附帶答案詳解
- 空調(diào)年度巡檢報(bào)告范文
- 培訓(xùn)學(xué)校 組織架構(gòu)及部門崗位職責(zé)
- 2023-2024學(xué)年浙江省金華市金東區(qū)九年級(上)期末語文試卷
- 靜脈輸液反應(yīng)急救流程
- 山東濰坊2024~2025第一學(xué)期高三階段性調(diào)研監(jiān)測考試英語試題含答案
- 反詐知識競賽題庫及答案(共286題)
- 2025屆江蘇省淮安市高三一模語文試題講評課件
評論
0/150
提交評論