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

Slides:



Advertisements
Similar presentations
Introduction to Java Reflection
Advertisements

Using Java™ Technology Reflection to Improve Design
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Building Java Programs Chapter 10
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Object Oriented Programming with Java
The List ADT Textbook Sections
Chapter 6 Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Freshers Week Java Course Part 2 An Introduction to Objects and Classes in Java Dr.-Ing. Norbert Völker Lab Assistant: Roxanna Turner.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Programming Abstract classes and Interfaces.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Java Review Interface, Casting, Generics, Iterator.
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
10/18/08 Matt Swatzell. What is Reflection?  Some Definitions….  Reflection is the process by which a program can modify its own behavior.  A program.
Java Generics.
Principles of Object-Oriented Software Development The language Java.
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
1 Java Reflection. 2 Java looking at Java l One of the unusual capabilities of Java is that a program can examine itself »You can determine the class.
1 Java object model Part 3: Serialization & Reflection.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
13-Jul-15 Reflection. 2 Java looking at Java One of the unusual capabilities of Java is that a program can examine itself You can determine the class.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
CPS 108 : Spring From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea  Not really a standard language like C++  Arguably.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
SEG4110 – Advanced Software Design and Reengineering TOPIC H Java Reflection.
Java Reflection. Compile-Time vs Run-Time Some data you know at compile time: int area = radius*radius*3.14; The “3.14” is set – known at compile time.
Object Oriented Programming in Java Lecture 13. Java Reflection Reflection is a feature unique to Java that allows an executing program to examine or.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Lecture 131 CS110 Lecture 13 Thursday, March 11, 2004 Announcements –hw5 due tonight –Spring break next week –hw6 due two weeks from tonight Agenda –questions.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Introduction to Java COM379 (Part-Time) University of Sunderland Harry R Erwin, PhD.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
RealTimeSystems Lab Jong-Koo, Lim
The AP Java Subset Topics. A Topics Primitive Types int double boolean.
Chapter 7: Cloning and RTTI
Intro to Java L. Grewe.
NESTED CLASSES REFLECTION PROXIES.
JAVA MULTIPLE CHOICE QUESTION.
CSE 413, Autumn 2002 Programming Languages
Programming Language Concepts (CIS 635)
Introduction to Java API
Computer Science II Exam 1 Review.
null, true, and false are also reserved.
Java Programming Language
Some Examples Reflection is used for many things:
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 { … }... }

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 { … }... }

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); }...

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); }...

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

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

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

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)

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

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

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

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

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

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

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.

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

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)

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

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

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...

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

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

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

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

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;

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[];

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;

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

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

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

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

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

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

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()

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

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()

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

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

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);

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

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

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.

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

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

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:

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

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:

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

2004 Java2