1 / 32

The Dynamic Properties of Java Reflection

The Dynamic Properties of Java Reflection. Shon Vick. Dynamic Facilities In Java. Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment.

alcina
Download Presentation

The Dynamic Properties of Java Reflection

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Dynamic Properties of Java Reflection Shon Vick

  2. Dynamic Facilities In Java • Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment. • For example, one major problem with C++ in a production environment is a side-effect of the way that code is implemented. • If company A produces a class library (a library of plug and play components) and company B buys it and uses it in their product, then if A changes its library and distributes a new release, B will almost certainly have to recompile and redistribute their own software.

  3. What this dynamic aspect implies • In an environment where the end user gets A and B's software independently (say A is an OS vendor and B is an application vendor) problems can result. • For example, if A distributes an upgrade to its libraries, then all of the software from B will break. It is possible to avoid this problem in C++, but it is extraordinarily difficult and it effectively means not using any of the language's OO features directly.

  4. Considerations • By making these interconnections between modules later, Java completely avoids these interconnection problems • Java makes the use of the object-oriented paradigm much more straightforward. • Libraries can freely add new methods and instance variables without any effect on their clients.

  5. The Class class As we have already briefly seen • In Java there is a class named Class, instances of which contain runtime class definitions. • In a C or C++ program, you have a pointer to an object but you don't know what type of object it is, there is no way to find out. • In Java, finding out based on the runtime type information is straightforward. • Class are loaded on an as needed basis with the class loader

  6. Reflection Allows • Determination of the class of an object. • Creation of an instance of a class whose name is not known until runtime. • Obtaining information about a class's modifiers, fields, methods, constructors, and superclasses. • Determination of constants and method declarations that belong to an interface

  7. Reflection Also Allows • Get and set the value of an object's field, even if the field name is unknown to your program until 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 array's components.

  8. Careful with that Ax • Don't use the reflection API when other tools more natural to the Java programming language would suffice • For example, if you use function pointers in another language, you might be tempted to use the Method objects of the reflection API in the same way. Resist the temptation! Your program will be easier to debug and maintain if you don't use Method objects. • Instead, you should define an interface, and then implement it in the classes that perform the needed action.

  9. Examining Classes • A way to get information about classes at runtime • For each class, the Java Runtime Environment (JRE) maintains an immutable Class object that contains information about the class. A Class object represents, or reflects, the class • To get this information you need to get the Class object that reflects the class

  10. Foo Bar The Example From Last Time You can retrieve a Class object in several ways: Class c = foo.getClass() // for some object named foo Bar b = new Bar(); Class c = b.getClass(); Class s = c.getSuperclass(); Good Quiz/Exam Question: Given an instance prints the names of the classes its inheritance hierarchy from least specific to most specific excluding Object

  11. An Example import java.lang.reflect.*; import java.awt.*; class SampleName { public static void main(String[] args) { Button b = new Button(); printName(b); } static void printName(Object o) { Class c = o.getClass(); String s = c.getName(); System.out.println(s); }}

  12. Discovering Class Modifiers • A class declaration may include the following modifiers: public, abstract, or final. The class modifiers precede the class keyword in the class definition. In the following example, the class modifiers are public and final public final Coordinate { // … }

  13. Discovering Class Modifiers • To identify the modifiers of a class at runtime you perform these steps: • Invoke getModifiers on a Class object to retrieve a set of modifiers • Check the modifiers by calling isPublic, isAbstract, and isFinal • Lets look at an example

  14. First Part of the Example import java.lang.reflect.*; import java.awt.*; class SampleModifier { public static void main(String[] args) { String s = new String(); printModifiers(s); } // … }

  15. Second part of the example // …. public static void printModifiers(Object o) { Class c = o.getClass(); int m = c.getModifiers(); if (Modifier.isPublic(m)) System.out.println("public"); if (Modifier.isAbstract(m)) System.out.println("abstract"); if (Modifier.isFinal(m)) System.out.println("final"); } }

  16. Interfaces and flexibility • An interface specifies a set of methods that an object can perform but leaves open how the object should implement those methods. • A class implements an interface by implementing all the methods contained in the interface. In contrast, inheritance by subclassing passes both a set of methods and their implementations from superclass to subclass. • A Java class can implement multiple interfaces but can only inherit from a single superclass. • Interfaces promote flexibility and reusability in code by connecting objects in terms of what they can do rather than how they do it.

  17. Identifying the Interfaces Implemented by a Class import java.lang.reflect.*; import java.io.*; class SampleInterface { public static void main(String[] args) { try { RandomAccessFile r = new RandomAccessFile("myfile", "r"); printInterfaceNames(r); } catch (IOException e) { System.out.println(e); } }

  18. Continuing static void printInterfaceNames(Object o) { Class c = o.getClass(); Class[] theInterfaces = c.getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); } }

  19. What Else Can We Do? • Considerations of other dynamic properties • Identifying Class Fields • Discovering Class Constructors • Obtaining Method Information • Manipulating Objects • Working with Arrays • Summary of Classes

  20. Identifying Class Fields • If you are writing an application such as a class browser, you might want to find out what fields belong to a particular class. • You can identify a class's fields by invoking the getFields method on a Class object. The getFields method returns an array of Field objects containing one object per accessible public field

  21. Rules of accessibility • A public field is accessible if it is a member of either • this class • a superclass of this class • an interface implemented by this class • an interface extended from an interface implemented by this class

  22. Manipulating Objects • Software development tools, such as GUI builders and debuggers, need to manipulate objects at runtime. • For example, a GUI builder may allow the end-user to select a Button from a menu of components, create the Button object, and then click the Button while running the application within the GUI builder

  23. Setting Field Values • To modify the value of a field you have to: • Create a Class object • Create a Field object by invoking getField on the Class • Invoke the appropriate set method on the Field object • The Field class provides several set methods. • Specialized methods, such as setBoolean and setInt, are for modifying primitive types. • If the field you want to change is an object invoke the set method. You can call set to modify a primitive type, but you must use the appropriate wrapper object for the value parameter

  24. An example import 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()); }

  25. Example Continued static void modifyWidth(Rectangle r, Integer 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); } } }

  26. Obtaining Method Information • To find out what public methods belong to a class, invoke the method named getMethods. • You can use a Method object to uncover a method's name, return type, parameter types, set of modifiers, and set of throwable exceptions. • With Method.invoke, you can even call the method itself.

  27. Invoking Methods • Create a Method object by invoking getMethod on the Class object. The getMethod method has two arguments: a String containing the method name, and an array of Class objects. • Invoke the method by calling invoke. The invoke method has two arguments: an array of argument values to be passed to the invoked method, and an object whose class declares or inherits the method

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

  29. Continuing public static String 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};

  30. Example try { concatMethod = c.getMethod("concat", parameterTypes); result = (String) concatMethod.invoke(firstWord, 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. Discovering Class Constructors • To create an instance of a class, you invoke a special method called a constructor. Like methods, constructors can be overloaded and are distinguished from one another by their signatures • You can get information about a class's constructors by invoking the getConstructors method, which returns an array of Constructor objects. • You can use the methods provided by the Constructor class to determine the constructor's name, set of modifiers, parameter types, and set of throwable exceptions. • You can also create a new instance of the Constructor object's class with the Constructor.newInstance method.

  32. References • This lecture comes mainly from the following two souces • http://java.sun.com/docs/books/tutorial/reflect/index.html • http://java.sun.com/docs/overviews/java/java-overview-1.html

More Related