Diapositive 1

Download Report

Transcript Diapositive 1

Java Virtual Machine. You'll want to use the reflection API if you are writing development to
Determine the class of an object.
Get information about a class's 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.
d set the value of an object's field, even if the field name is unknown to your program until ru
Invoke a method on an object, even if the method is not known until runtime.
ray, whose size and component type are not known until runtime, and then modify the array
e, you might be tempted to use the Method objects of the reflection API in the same way. Re
rgument constructor, you can invoke the newInstance method on a Class object. The newInstance method throws a NoSuc
stance of the Rectangle class using the no-argument constructor by calling the newInstance method:
oid main(String[] args) { Rectangle r = (Rectangle) createObject("java.awt.Rectangle"); System.out.println(r.toString()); } static Object createObject(String className)
•
import java.lang.reflect.*; import java.awt.*; class SampleInstance { public
static void main(String[] args) { Rectangle rectangle; 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");
intArgsConstructor = 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, Object[] 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) {
System.out.println(e); } catch (IllegalArgumentException e) {
System.out.println(e); } catch (InvocationTargetException e) {
System.out.println(e); } return object; } }
t allows the user to select and then invoke methods during a debugging session. Since you
t to invoke. See the section Retrieving Class Objects for more information.
e Class object. The getMethod method has two arguments: a String containing the method name, and an array of Class objects. Each element in the array corresponds to a parame
d 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.
oke { public static void main(String[] args) { String firstWord = "Hello "; String secondWord =