Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reflection & Generics in JDK1.5 / J.J. Hou / /

Similar presentations


Presentation on theme: "Reflection & Generics in JDK1.5 / J.J. Hou / /"— Presentation transcript:

1

2 Reflection & Generics in JDK1.5 / J.J. Hou / /

3 2004 Java2.Generics JDK1.3 Generics Java JDK1.5 Java Library JDK1.5 Generics

4 2004 Java2.Reflection Reflection Java Component-based programming Javabean, deSerialization, RMI Remote Method Invocation Reflection APIs Reflection

5 2004 Java2 (homogenous) (heterogenous) C++ STL list myList; myList.push_back(3); Java Collections LinkedList myList = new LinkedList(); myList.add(new Double(4.4)); myList.add(new String("jjhou")); int -list Object Generics

6 2004 Java2 in Java Java C++ " " Generics in Java LinkedList myList = new LinkedList (); myList.add(new Integer(4)); myList.add(new Integer(7)); myList.add(new String("hello")); //Error! Generics

7 2004 Java2 Polymorphism Java Collections LinkedList Stroke Rect Circle Object LinkedList myList = new LinkedList (); 18 2b2b 2c2c 5 2c2c Stroke Rect Circle x:Integer y:Integer r:Integer l:Integer t:Integer w:Integer h:Integer w:Integer ia:ArrayList Generics

8 2004 Java2 Polymorphism Shape Object Stroke Rect Circle x:Integer y:Integer r:Integer l:Integer t:Integer w:Integer h:Integer w:Integer ia:ArrayList LinkedList myList = new LinkedList (); 18 2b2b 2c2c 5 2c2c Stroke Rect Circle Generics

9 2004 Java2 Generics Java Collections Object LinkedList myList = new LinkedList(); myList.add(new Integer(0)); myList.add(new Integer(1)); Integer tempi = (Integer)myList.iterator().next(); LinkedList myList = new LinkedList(); myList.add(new Integer(0)); myList.add(new Integer(1)); Integer tempi = (Integer)myList.iterator().next(); Generics

10 2004 Java2 Generics generic types Java collection LinkedList iList = new LinkedList (); iList.add(new Integer(0)); iList.add(new Integer(1)); Integer tempi = iList.iterator().next(); LinkedList iList = new LinkedList (); iList.add(new Integer(0)); iList.add(new Integer(1)); Integer tempi = iList.iterator().next(); Generics

11 2004 Java2 Java/C++ template class list {... }; template class list {... }; #include list li; list ls; list ld; #include list li; list ls; list ld; class list; // string list li; list ls; list ld; list li; list ls; list ld; class list; // int class list; // double public class LinkedList {... }; public class LinkedList {... }; import java.util.* LinkedList...; import java.util.* LinkedList...; public class LinkedList {... }; public class LinkedList {... }; import java.util.* LinkedList...; import java.util.* LinkedList...; list java.util.LinkedList.java.exe.class C++ Java Generics

12 2004 Java2 Generics Java JDK1.3 + GJ (a Generic Java language extension) %GJClasses%\gjc.Main + Collections %GJClasses%\*.class GP JDK1.4+JSR14 (Adding Generics to Java Language) %JSR14DISTR%\javac.jar + Collections %JSR14DISTR%\collect.jar GP JDK1.5 GP Java Library GJ JSR14 Generics

13 2004 Java2 Java Generics Generic Classes java.util (collections) Generic Algorithms (methods) methods in java.util.Collection Generic Classes Generic Algorithms (methods) Generics

14 2004 Java2 JDK1.5 Generic Classes/Algorithms ArrayList strList = new ArrayList (); strList.add("zero"); strList.add("one"); strList.add("two"); strList.add("five"); System.out.println(strList); // [zero, one, two, five] String str = Collections.max(strList); Collections.sort(strList); ArrayList strList = new ArrayList (); strList.add("zero"); strList.add("one"); strList.add("two"); strList.add("five"); System.out.println(strList); // [zero, one, two, five] String str = Collections.max(strList); Collections.sort(strList); static methods Generics

15 2004 Java2 Boxing & UnBoxing LinkedList iList = new LinkedList (); iList.add(new Integer(0)); iList.add(new Integer(1)); iList.add(new Integer(5)); iList.add(new Integer(2)); LinkedList iList = new LinkedList (); iList.add(new Integer(0)); iList.add(new Integer(1)); iList.add(new Integer(5)); iList.add(new Integer(2)); LinkedList iList = new LinkedList (); iList.add(0);//boxing iList.add(1); iList.add(5); iList.add(2); int i = iList.get(2);//un-boxing LinkedList iList = new LinkedList (); iList.add(0);//boxing iList.add(1); iList.add(5); iList.add(2); int i = iList.get(2);//un-boxing Generics object

16 2004 Java2 JDK1.5, java.util.Map Generics public interface Map { V get(Object key); V put(K key, V value); V remove(Object key); void putAll(Map t); interface Entry { … }... } public interface Map { V get(Object key); V put(K key, V value); V remove(Object key); void putAll(Map t); interface Entry { … }... }

17 2004 Java2 JDK1.4, java.util.Map Generics public interface Map { Object get(Object key); Object put(Object key, Object value); Object remove(Object key); void putAll(Map t); interface Entry { … }... } public interface Map { Object get(Object key); Object put(Object key, Object value); Object remove(Object key); void putAll(Map t); interface Entry { … }... }

18 2004 Java2 JDK1.5, java.util.ArrayList Generics public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable { private transient E[] elementData; private int size; public ArrayList(Collection c) { size = c.size(); // Allow 10% room for growth elementData = (E[])new Object[ (int)Math.min((size*110L)/100, Integer.MAX_VALUE)]; c.toArray(elementData); }... public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable { private transient E[] elementData; private int size; public ArrayList(Collection c) { size = c.size(); // Allow 10% room for growth elementData = (E[])new Object[ (int)Math.min((size*110L)/100, Integer.MAX_VALUE)]; c.toArray(elementData); }...

19 2004 Java2 JDK1.4, java.util.ArrayList Generics public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable { private transient Object elementData[]; private int size; public ArrayList(Collection c) { size = c.size(); // Allow 10% room for growth elementData = new Object[ (int)Math.min((size*110L)/100, Integer.MAX_VALUE)]; c.toArray(elementData); }... public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable { private transient Object elementData[]; private int size; public ArrayList(Collection c) { size = c.size(); // Allow 10% room for growth elementData = new Object[ (int)Math.min((size*110L)/100, Integer.MAX_VALUE)]; c.toArray(elementData); }...

20 2004 Java2 JDK1.5 Generic Classes Shape Object Stroke Rect Circle x:T y:T r:T l:T t:T w:T h:T w:T a:ArrayList LinkedList sList = new LinkedList (); 18 2b2b 2c2c 5 2c2c Stroke Rect Circle TTW,T LinkedList sList = new LinkedList (); sList.add(new Stroke (…)); sList.add(new Rect (…)); sList.add(new Circle (…)); LinkedList sList = new LinkedList (); sList.add(new Stroke (…)); sList.add(new Rect (…)); sList.add(new Circle (…)); draw() len() compareTo() Generics

21 2004 Java2 JDK1.5 Generic Classes public abstract class Shape implements Comparable { public abstract void draw(); public abstract double len(); public int compareTo(Shape o) { return (this.len() < o.len() ? -1 : (this.len() == o.len() ? 0 : 1)); } public abstract class Shape implements Comparable { public abstract void draw(); public abstract double len(); public int compareTo(Shape o) { return (this.len() < o.len() ? -1 : (this.len() == o.len() ? 0 : 1)); } public class Stroke extends Shape implements Serializable { W width; ArrayList a; public double len() {... } public void draw() {... } } public class Stroke extends Shape implements Serializable { W width; ArrayList a; public double len() {... } public void draw() {... } } Template Method max() ! class <> generic class Generics public final class Integer extends Number implements Comparable

22 2004 Java2 JDK1.5 Generic Classes public class Rect extends Shape implements Serializable { T l,t,w,h; public void draw() {... } public double len() {... } } public class Rect extends Shape implements Serializable { T l,t,w,h; public void draw() {... } public double len() {... } } public class Circle extends Shape implements Serializable { T x,y,r; public double len() {... } public void draw() {... } } public class Circle extends Shape implements Serializable { T x,y,r; public double len() {... } public void draw() {... } } ! class <> generic class Generics Class

23 2004 Java2 JDK1.5 Generic Algorithms // in someone class public static T gMethod (List list) {... } // in someone class public static T gMethod (List list) {... } public static > T gMethod (List list) {... } public static > T gMethod (List list) {... } public static List gMethod (List list) { return list; // } public static List gMethod (List list) { return list; // } method <> generic method "bounded type parameter" " JDK 1.5 method '?' Generics (1) (2) (3)

24 2004 Java2 JDK1.4, java.util.Collections.max() #001 public class Collections { # #003 public static #004 // JDK1.5 #005 Object max(Collection coll) { #006 Iterator i = coll.iterator(); #007 Comparable candidate = (Comparable)(i.next()); #008 #009 while(i.hasNext()) { #010 Comparable next = (Comparable)(i.next()); #011 if (next.compareTo(candidate) > 0) #012 candidate = next; #013 } #014 return candidate; #015 } # #017 } // of Collections #001 public class Collections { # #003 public static #004 // JDK1.5 #005 Object max(Collection coll) { #006 Iterator i = coll.iterator(); #007 Comparable candidate = (Comparable)(i.next()); #008 #009 while(i.hasNext()) { #010 Comparable next = (Comparable)(i.next()); #011 if (next.compareTo(candidate) > 0) #012 candidate = next; #013 } #014 return candidate; #015 } # #017 } // of Collections Generics

25 2004 Java2 JDK1.5, java.util.Collections.max() #001 public class Collections { # #003 public static #004 > #005 T max(Collection coll) { #006 Iterator i = coll.iterator(); #007 T candidate = i.next(); #008 #009 while(i.hasNext()) { #010 T next = i.next(); #011 if (next.compareTo(candidate) > 0) #012 candidate = next; #013 } #014 return candidate; #015 } # #017 } // of Collections #001 public class Collections { # #003 public static #004 > #005 T max(Collection coll) { #006 Iterator i = coll.iterator(); #007 T candidate = i.next(); #008 #009 while(i.hasNext()) { #010 T next = i.next(); #011 if (next.compareTo(candidate) > 0) #012 candidate = next; #013 } #014 return candidate; #015 } # #017 } // of Collections Generics

26 2004 Java2 JDK1.5, java.util.Collections.max() max() Collection object 2. Collection object T-derived object 3. T Object Java 4. T Comparable 5. Comparable supertype of T 6. max() T object Generics

27 2004 Java2 Introspection (,, ) Reflection "look inside" classes introspection "the ability of the program to examine itself" Java introspection (1) Static Introspection :.class file inspection (2) Dynamic Introspection : Reflection API

28 2004 Java2 Reflection Reflection Java Reflection APIs class package type parameters superclass implemented interfaces inner classes, outer class, fields constructors methods modifiers instances fields methods

29 2004 Java2 Reflection Test.class disk Test class definition (Class object for Test class) dynamic loading by class loader (a ClassLoader object) virtual machine environment class JRE immutable Class object class. Reflection APIs

30 2004 Java2 Reflection APIs Reflection Reflection API object class. class modifiers, fields, methods, constructors, superclasses. interface constants method declarations. class. object's field,. invoke object' method. array, (component type) array.

31 2004 Java2 Reflection APIs Reflection Core Reflection API object run-time class public members object public fields, methods, constructors Java Beans services lightweight tools object inspectors Class methods: getField, getMethod, getConstructor, getFields, getMethods, getConstructors classes Field, Method, Constructor instances class members class file class development tools interpreters, inspectors, class browsers, run-time services Java Object Serialization Class methods: getDeclaredField, getDeclaredMethod, getDeclaredConstructor, getDeclaredFields, getDeclaredMethods, getDeclaredConstructors classes Field, Method, Constructor instances

32 2004 Java2 Reflection APIs Reflection Reflection API java.lang.Class java.lang.reflect classes: (1) Field, (2) Method, (3) Constructor, (4) Array, (5) Modifier classes / interfaces (corresponding) Array methods,, arrays Modifier methods modifiers ( static, public)

33 2004 Java2 Object class Reflection public class Object { public final native Class getClass(); public native int hashCode(); public boolean equals(Object obj) { return (this == obj); } protected native Object clone() throws CloneNotSupportedException; public String toString() { return getClass().getName() + + Integer.toHexString(hashCode()); } public final native void notify(); public final native void notifyAll(); public final native void wait(long timeout) throws InterruptedException; public final void wait(long timeout, int nanos) throws InterruptedException; public final void wait() throws InterruptedException; protected void finalize() throws Throwable { } } public class Object { public final native Class getClass(); public native int hashCode(); public boolean equals(Object obj) { return (this == obj); } protected native Object clone() throws CloneNotSupportedException; public String toString() { return getClass().getName() + + Integer.toHexString(hashCode()); } public final native void notify(); public final native void notifyAll(); public final native void wait(long timeout) throws InterruptedException; public final void wait(long timeout, int nanos) throws InterruptedException; public final void wait() throws InterruptedException; protected void finalize() throws Throwable { } } Object class Java classes root java.lang.Object java.lang.Class

34 2004 Java2 Class class Reflection Class instance Java classes interfaces enum, annotation, array, primitive Java types (boolean, byte, char, short, int, long, float, double), void Class objects. Class public constructor objects classes class loader defineClass() Java Virtual Machine Class object object class void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); } void class literal Class object System.out.println("The name of class Foo is: "+Foo.class.getName()); Class instance Java classes interfaces enum, annotation, array, primitive Java types (boolean, byte, char, short, int, long, float, double), void Class objects. Class public constructor objects classes class loader defineClass() Java Virtual Machine Class object object class void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); } void class literal Class object System.out.println("The name of class Foo is: "+Foo.class.getName()); java.lang.Object java.lang.Class

35 2004 Java2 Class class Reflection public String toString() { return ( isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) + getName(); } public String toString() { return ( isInterface() ? "interface " : (isPrimitive() ? "" : "class ")) + getName(); } public final class Class implements java.io.Serializable, java.lang.reflect.GenericDeclaration, java.lang.reflect.Type, java.lang.reflect.AnnotatedElement { private Class() {} public final class Class implements java.io.Serializable, java.lang.reflect.GenericDeclaration, java.lang.reflect.Type, java.lang.reflect.AnnotatedElement { private Class() {} Class public constructor objects classes loadClass(...) class loader defineClass(...) Java Virtual Machine class Class object...

36 2004 Java2 Class class Reflection From getClass(). String str = "abc"; Class c1 = str.getClass(); From the method Class.getSuperclass() Button b = new Button(); Class c1 = b.getClass(); Class c2 = c1.getSuperclass(); BTW getSuperclass() returns null for the class Object. From the static method Class.forName() Class c1 = Class.forName ("java.lang.String"); Class c2 = Class.forName ("java.awt.Button"); Class c3 = Class.forName ("java.util.LinkedList$Entry"); Class c4 = Class.forName ("I"); Class c5 = Class.forName ("[I"); From getClass(). String str = "abc"; Class c1 = str.getClass(); From the method Class.getSuperclass() Button b = new Button(); Class c1 = b.getClass(); Class c2 = c1.getSuperclass(); BTW getSuperclass() returns null for the class Object. From the static method Class.forName() Class c1 = Class.forName ("java.lang.String"); Class c2 = Class.forName ("java.awt.Button"); Class c3 = Class.forName ("java.util.LinkedList$Entry"); Class c4 = Class.forName ("I"); Class c5 = Class.forName ("[I"); From the.class syntax Class c1 = String.class; Class c2 = java.awt.Button.class; Class c3 = Main.InnerClass.class; Class c4 = int.class; Class c5 = int[].class; From the primitive wrapper classes Class c1 = Boolean.TYPE; Class c2 = Byte.TYPE; Class c3 = Character.TYPE; Class c4 = Short.TYPE; Class c5 = Integer.TYPE; Class c6 = Long.TYPE; Class c7 = Float.TYPE; Class c8 = Double.TYPE; Class c9 = Void.TYPE; From the.class syntax Class c1 = String.class; Class c2 = java.awt.Button.class; Class c3 = Main.InnerClass.class; Class c4 = int.class; Class c5 = int[].class; From the primitive wrapper classes Class c1 = Boolean.TYPE; Class c2 = Byte.TYPE; Class c3 = Character.TYPE; Class c4 = Short.TYPE; Class c5 = Integer.TYPE; Class c6 = Long.TYPE; Class c7 = Float.TYPE; Class c8 = Double.TYPE; Class c9 = Void.TYPE; java.lang.Class objects

37 2004 Java2 ClassLoader class Reflection class loader object classes ClassLoader abstract class class class loader (locate) (generate) class definition "class file" Class object getClassLoader(), reference to Class object ClassLoader ClassLoader class delegation model classes resources instance associated parent class loader class resource ClassLoader instance (delegate) parent class loader class resource Virtual machine class loader bootstrap class loader parent ClassLoader instance parent Java virtual machine platform-dependent local file system classes UNIX virtual machine CLASSPATH classes classes method defineClass(String, byte[], int, int) an array of bytes Class instance class Class.newInstance() instances class loader object classes ClassLoader abstract class class class loader (locate) (generate) class definition "class file" Class object getClassLoader(), reference to Class object ClassLoader ClassLoader class delegation model classes resources instance associated parent class loader class resource ClassLoader instance (delegate) parent class loader class resource Virtual machine class loader bootstrap class loader parent ClassLoader instance parent Java virtual machine platform-dependent local file system classes UNIX virtual machine CLASSPATH classes classes method defineClass(String, byte[], int, int) an array of bytes Class instance class Class.newInstance() instances

38 2004 Java2 Class ( ) Package getPackage() String getName() TypeVariable [] getTypeParameters() Class getSuperClass() Class[] getInterfaces() Class[] getDeclaredClasses() Class getDeclaringClass() Consructor[] getDeclaredConstructors() Method[] getDeclaredMethods() Field[] getDeclaredFields() but import lib... Package getPackage() String getName() TypeVariable [] getTypeParameters() Class getSuperClass() Class[] getInterfaces() Class[] getDeclaredClasses() Class getDeclaringClass() Consructor[] getDeclaredConstructors() Method[] getDeclaredMethods() Field[] getDeclaredFields() but import lib... package java.util; public class LinkedList extends AbstractSequentialList implements List, Queue, Cloneable, java.io.Serializable { private static class Entry { … } public LinkedList() { … } public LinkedList(Collection c) { … } public E getFirst() { … } public E getLast() { … } private transient Entry header = …; private transient int size = 0; } Reflection Class methods

39 2004 Java2 tName() Reflection static String tName(String nm, Hashtable ht) { String yy; String arr; if (nm.charAt(0) != '[') { int i = nm.lastIndexOf("."); if (i == -1) return nm; // primitive type, ignore it. else { yy = nm.substring(i+1); if (ht != null) ht.put(nm, yy); return yy; }... static String tName(String nm, Hashtable ht) { String yy; String arr; if (nm.charAt(0) != '[') { int i = nm.lastIndexOf("."); if (i == -1) return nm; // primitive type, ignore it. else { yy = nm.substring(i+1); if (ht != null) ht.put(nm, yy); return yy; }... java.lang.Integer lastIndexOf(".") yy (class name part) nm (fully qualified name) Integerjava.lang.Integer keyvalue Hashtable

40 2004 Java2 package Package getPackage() package java.util; Class c = null; c = Class.forName(args[0]); Package p; p = c.getPackage(); if (p != null) System.out.println("package "+p.getName()+";"); Class c = null; c = Class.forName(args[0]); Package p; p = c.getPackage(); if (p != null) System.out.println("package "+p.getName()+";"); Reflection 1 package java.util;

41 2004 Java2 import list Reflection ff = c.getDeclaredFields(); for (int i = 0; i < ff.length; i++) x = tName(ff[i].getType().getName(), classRef); cn = c.getDeclaredConstructors(); for (int i = 0; i < cn.length; i++) { Class cx[] = cn[i].getParameterTypes(); for (int j = 0; j < cx.length; j++) x = tName(cx[j].getName(), classRef); } mm = c.getDeclaredMethods(); for (int i = 0; i < mm.length; i++) { x = tName(mm[i].getReturnType().getName(), classRef); Class cx[] = mm[i].getParameterTypes(); for (int j = 0; j < cx.length; j++) x = tName(cx[j].getName(), classRef); } classRef.remove(c.getName()); (1) fields type hashtable (2) ctors parameters type hashtable (3) methods return/parameters type hashtable (4) hashtable Constructor cn[]; Method mm[]; Field ff[];

42 2004 Java2 import list Reflection import java.lang.Object; import java.util.Collection; import java.util.Set; import java.util.ListIterator; import java.lang.Object; import java.util.LinkedList$Entry; import java.util.Collection; import java.io.ObjectOutputStream; import java.io.ObjectInputStream;

43 2004 Java2 class name modifier String getName() public class LinkedList Reflection 2 c = Class.forName(args[0]); int mod = c.getModifiers(); System.out.print(Modifier.toString(mod)); // modifier if (Modifier.isInterface(mod)) System.out.print(" "); //"interface" modifier else System.out.print(" class "); // "class" System.out.print(tName(c.getName(), null)); //class c = Class.forName(args[0]); int mod = c.getModifiers(); System.out.print(Modifier.toString(mod)); // modifier if (Modifier.isInterface(mod)) System.out.print(" "); //"interface" modifier else System.out.print(" class "); // "class" System.out.print(tName(c.getName(), null)); //class public class LinkedList public final class Class public abstract interface Map

44 2004 Java2 Type Parameters TypeVariable [] getTypeParameters() TypeVariable [] getTypeParameters() package java.util public class LinkedList Reflection TypeVariable [] tv; tv = c.getTypeParameters(); //warning: unchecked conversion for (int i = 0; i < tv.length; i++) { x = tName(tv[i].getName(), null); // E,K,V... if (i == 0) // System.out.print("<" + x); else // System.out.print("," + x); if (i == tv.length-1) // System.out.println(">"); } TypeVariable [] tv; tv = c.getTypeParameters(); //warning: unchecked conversion for (int i = 0; i < tv.length; i++) { x = tName(tv[i].getName(), null); // E,K,V... if (i == 0) // System.out.print("<" + x); else // System.out.print("," + x); if (i == tv.length-1) // System.out.println(">"); } public class LinkedList public abstract interface Map 3

45 2004 Java2 Super Class Class getSuperClass() public class LinkedList extends AbstractSequentialList Reflection Class supClass; supClass = c.getSuperclass(); if (supClass != null) // super class System.out.print(" extends" + tName(supClass.getName(),classRef)); Class supClass; supClass = c.getSuperclass(); if (supClass != null) // super class System.out.print(" extends" + tName(supClass.getName(),classRef)); public class LinkedList extends AbstractSequentialList, implements List, Queue, Cloneable, Serializable, { 4

46 2004 Java2 Implemented Interfaces Class[] getInterfaces() public class LinkedList extends AbstractSequentialList implements List, Queue, Cloneable, java.io.Serializable Reflection Class cc[]; Class ctmp; // interfaces cc = c.getInterfaces(); if (cc.length != 0) System.out.print(", \r\n" + " implements "); for (Class cite : cc) System.out.print(tName(cite.getName(), null)+", "); Class cc[]; Class ctmp; // interfaces cc = c.getInterfaces(); if (cc.length != 0) System.out.print(", \r\n" + " implements "); for (Class cite : cc) System.out.print(tName(cite.getName(), null)+", "); 5 public class LinkedList extends AbstractSequentialList, implements List, Queue, Cloneable, Serializable, { JDK1.5, for loop

47 2004 Java2 DeclaredClasses (inner classes) DeclaringClass (outer class) Class[] getDeclaredClasses() Class getDeclaringClass() Class[] getDeclaredClasses() Class getDeclaringClass() public class LinkedList... { private static class Entry { … } class name: LinkedList$Entry Reflection 6 cc = c.getDeclaredClasses(); // inner classes for (Class cite : cc) System.out.println(tName(cite.getName(), null)); ctmp = c.getDeclaringClass(); // outer classes if (ctmp != null) System.out.println(ctmp.getName()); cc = c.getDeclaredClasses(); // inner classes for (Class cite : cc) System.out.println(tName(cite.getName(), null)); ctmp = c.getDeclaringClass(); // outer classes if (ctmp != null) System.out.println(ctmp.getName()); LinkedList$Entry LinkedList$ListItr Map$Entry

48 2004 Java2 Declared Constructors (1) Consructor[] getDeclaredConstructors() Consructor[] getDeclaredConstructors() public class LinkedList... { public LinkedList() { … } public LinkedList(Collection c) { … } Reflection 7

49 2004 Java2 Declared Constructors (2) Reflection Constructor cn[]; cn = c.getDeclaredConstructors(); for (int i = 0; i < cn.length; i++) { int md = cn[i].getModifiers(); System.out.print(" " + Modifier.toString(md) + " " + cn[i].getName()); Class cx[] = cn[i].getParameterTypes(); System.out.print("("); for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), null)); if (j < (cx.length - 1)) System.out.print(", "); } System.out.print(")"); System.out.println("G: " + cn[i].toGenericString()); } Constructor cn[]; cn = c.getDeclaredConstructors(); for (int i = 0; i < cn.length; i++) { int md = cn[i].getModifiers(); System.out.print(" " + Modifier.toString(md) + " " + cn[i].getName()); Class cx[] = cn[i].getParameterTypes(); System.out.print("("); for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), null)); if (j < (cx.length - 1)) System.out.print(", "); } System.out.print(")"); System.out.println("G: " + cn[i].toGenericString()); } public java.util.LinkedList(Collection) G: public java.util.LinkedList(java.util.Collection ) public java.util.LinkedList() G: public java.util.LinkedList()

50 2004 Java2 Declared Methods (1) Method[] getDeclaredMethods() Method[] getDeclaredMethods() public class LinkedList... { public E getFirst() { … } public E getLast() { … } Reflection 8

51 2004 Java2 Declared Methods (2) Reflection Method mm[]; mm = c.getDeclaredMethods(); for (int i = 0; i < mm.length; i++) { int md = mm[i].getModifiers(); System.out.print(" "+Modifier.toString(md)+" "+ tName(mm[i].getReturnType().getName(), null)+" "+ mm[i].getName()); Class cx[] = mm[i].getParameterTypes(); System.out.print("("); for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), null)); if (j < (cx.length - 1)) System.out.print(", "); } System.out.print(")"); System.out.println("G: " + mm[i].toGenericString()); } Method mm[]; mm = c.getDeclaredMethods(); for (int i = 0; i < mm.length; i++) { int md = mm[i].getModifiers(); System.out.print(" "+Modifier.toString(md)+" "+ tName(mm[i].getReturnType().getName(), null)+" "+ mm[i].getName()); Class cx[] = mm[i].getParameterTypes(); System.out.print("("); for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), null)); if (j < (cx.length - 1)) System.out.print(", "); } System.out.print(")"); System.out.println("G: " + mm[i].toGenericString()); } public Object get(int) G: public E java.util.LinkedList.get(int) public int size() G: public int java.util.LinkedList.size()

52 2004 Java2 Declared Fields (1) Field[] getDeclaredFields() Field[] getDeclaredFields() public class LinkedList... { private transient Entry header = …; private transient int size = 0; } Reflection 9

53 2004 Java2 Declared Fields (2) Reflection Field ff[]; ff = c.getDeclaredFields(); for (int i = 0; i < ff.length; i++) { int md = ff[i].getModifiers(); System.out.println(" "+Modifier.toString(md)+" "+ tName(ff[i].getType().getName(), null) +" "+ ff[i].getName()+";"); System.out.println("G: " + ff[i].toGenericString()); } Field ff[]; ff = c.getDeclaredFields(); for (int i = 0; i < ff.length; i++) { int md = ff[i].getModifiers(); System.out.println(" "+Modifier.toString(md)+" "+ tName(ff[i].getType().getName(), null) +" "+ ff[i].getName()+";"); System.out.println("G: " + ff[i].toGenericString()); } private transient LinkedList$Entry header; G: private transient java.util.LinkedList.java.util.LinkedList$Entry java.util.LinkedList.header private transient int size; G: private transient int java.util.LinkedList.size

54 2004 Java2 object (class name ) Reflection 1. no argument 2. with arguments Class c = Class.forName("DynTest"); Object obj = null; obj = c.newInstance(); // System.out.println(obj); Class c = Class.forName("DynTest"); Object obj = null; obj = c.newInstance(); // System.out.println(obj); Class c = Class.forName("DynTest"); Class[] pTypes = new Class[] { double.class, int.class }; Constructor ctor = c.getConstructor(pTypes); // parameter list ctor Object obj = null; Object[] arg = new Object[] { , 125}; // obj = ctor.newInstance(arg); System.out.println(obj); Class c = Class.forName("DynTest"); Class[] pTypes = new Class[] { double.class, int.class }; Constructor ctor = c.getConstructor(pTypes); // parameter list ctor Object obj = null; Object[] arg = new Object[] { , 125}; // obj = ctor.newInstance(arg); System.out.println(obj);

55 2004 Java2 / object's fields (field's name ) Reflection 1. "field class" Class object c 2. c.getField(_) Field object f field name 3. (Type)f.get(obj) f.set(obj, newValue) calling obj newValue

56 2004 Java2 / object's fields (field's name ) Reflection public class Test { public double d; public static void main(String args[]) { Class c = Class.forName("Test"); Field f = c.getField("d"); Test obj = new Test(); System.out.println("d= " + (Double)f.get(obj)); f.set(obj, 12.34); System.out.println("d= " + obj.d); } public class Test { public double d; public static void main(String args[]) { Class c = Class.forName("Test"); Field f = c.getField("d"); Test obj = new Test(); System.out.println("d= " + (Double)f.get(obj)); f.set(obj, 12.34); System.out.println("d= " + obj.d); } Test.class 1 2 3

57 2004 Java2 object's methods (method's name ) 1. "method class" Class object c 2. c.getMethod(_,_) Method object m signature (method name & parameters list) 3. m.invoke(_,_) calling object arguments list.

58 2004 Java2 signature Method object object's methods ( 1) public int add(int a, int b) { return a + b; } public static void main(String args[]) { Class c = Class.forName("Test"); Class ptypes[] = new Class[2]; ptypes[0] = Integer.TYPE; ptypes[1] = Integer.TYPE; Method m = c.getMethod("add",ptypes); Test obj = new Test(); Object args[] = new Object[2]; arg[0] = new Integer(37); arg[1] = new Integer(47); Object r = m.invoke(obj, arg); Integer rval = (Integer)r; System.out.println(rval.intValue()); } public int add(int a, int b) { return a + b; } public static void main(String args[]) { Class c = Class.forName("Test"); Class ptypes[] = new Class[2]; ptypes[0] = Integer.TYPE; ptypes[1] = Integer.TYPE; Method m = c.getMethod("add",ptypes); Test obj = new Test(); Object args[] = new Object[2]; arg[0] = new Integer(37); arg[1] = new Integer(47); Object r = m.invoke(obj, arg); Integer rval = (Integer)r; System.out.println(rval.intValue()); } Test obj = new Test(); obj.add(37, 47) add(int a, int b) Method::invoke(x,x) calling object argument list. (Object[ ]) Object. Test.class 1 2 3

59 2004 Java2 signature Method object object's methods ( 2) public String func(String s, Hashtable ht) { System.out.println("func invoked"); return s; } public static void main(String args[]) { Class c = Class.forName("Test"); Class ptypes[] = new Class[2]; ptypes[0] = Class.forName("java.lang.String"); ptypes[1] = Class.forName("java.util.Hashtable"); Method m = c.getMethod("func",ptypes); Test obj = new Test(); Object args[] = new Object[2]; arg[0] = new String("Hello,world"); arg[1] = null; Object r = m.invoke(obj, arg); Integer rval = (String)r; System.out.println(rval); } public String func(String s, Hashtable ht) { System.out.println("func invoked"); return s; } public static void main(String args[]) { Class c = Class.forName("Test"); Class ptypes[] = new Class[2]; ptypes[0] = Class.forName("java.lang.String"); ptypes[1] = Class.forName("java.util.Hashtable"); Method m = c.getMethod("func",ptypes); Test obj = new Test(); Object args[] = new Object[2]; arg[0] = new String("Hello,world"); arg[1] = null; Object r = m.invoke(obj, arg); Integer rval = (String)r; System.out.println(rval); } Test obj = new Test(); obj.tName("Hello", null) tName(String s, Hashtable ht) Method::invoke(x,x) calling object argument list. (Object[ ]) Object. Test.class 1 2 3

60 2004 Java2 Reflection APIs forName getName getDeclaredFields getDeclaredMethods getDeclaredConstructors getDeclaredClasses getDeclaringClass getModifiers getSuperClass getGenericInterfaces getGenericSuperclass getInterfaces getPackage isArray isEnum isPrimitive isSynthetic isAnnotation isInterface getTypeParameters newInstance forName getName getDeclaredFields getDeclaredMethods getDeclaredConstructors getDeclaredClasses getDeclaringClass getModifiers getSuperClass getGenericInterfaces getGenericSuperclass getInterfaces getPackage isArray isEnum isPrimitive isSynthetic isAnnotation isInterface getTypeParameters newInstance Class class: getName getParameterTypes getModifiers toGenericString getName getParameterTypes getModifiers toGenericString Constructor class: getName getParameterTypes getReturnType getModifiers toGenericString invoke getName getParameterTypes getReturnType getModifiers toGenericString invoke Method class: getName getType getModifiers getxxx setxxx toGenericString getName getType getModifiers getxxx setxxx toGenericString Field class: IsInterface Isxxx toString IsInterface Isxxx toString Modifier class: [empty] Type class: getName Package class: getName getGenericDeclaration getName getGenericDeclaration TypeVariable class:

61 2004 Java2 Java Library c:\jdk150\src\java\lang\Class.java *.class c:\jdk150\jre\lib\rt.jar Java Library classes c:\somewhere\Test.java c:\jdk150\jre\lib\endorsed classloader.jar *.class e:\java\lang foo.jar.zip java\lang foo.jar endorsed classes

62 2004 Java2 Java Library.java.class xxx.jar java\lang endorsed class loader jj-java.jar jj-javax.jar rem "rejava.bat" usage : rem (1) enter the directory which you want to rewrite java source. rem (2) backup the original java source "x.java" to "x.java.ori". rem (3) modify java source. rem (4) rejava path filename (no extension name) rem ex: rejava javax\swing\text GapContent del c:\jdk150\jre\lib\endorsed\jj-javax.jar del c:\jdk150\jre\lib\endorsed\jj-java.jar javac %2.java move *.class e:\%1 e: cd e:\ jar cvfM c:\jdk150\jre\lib\endorsed\jj-javax.jar javax jar cvfM c:\jdk150\jre\lib\endorsed\jj-java.jar java dir e:\%1 dir c:\jdk150\jre\lib\endorsed c:

63 2004 Java2 "Java " Java Reflection in Action, by Ira R. Forman and Nate Forman Manning Publications Co. "Take an in-depth look at the Java Reflection API" -- Learn about the new Java 1.1 tools for finding out information about classes "Take a look inside Java classes" -- Learn to deduce properties of a Java class from inside a Java program

64 2004 Java2


Download ppt "Reflection & Generics in JDK1.5 / J.J. Hou / /"

Similar presentations


Ads by Google