Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts

Friday, 24 June 2011

new vs newInstance() performace

Everybody knows (or should) that any operation performed using reflections is bound to be slower than its static, compiled counterpart. But as jdk versions are increasing, this time is decreasing.

I was making the classic micro-benchmarking error of not warming up the VM, so here’s the slightly modified version of the code:

public class TheCostOfReflection {

public static void main(String[] args) throws Exception {
int nObjects = 100;
Object[] objects = new Object[nObjects];

// warm up a bit
int warmupLoops = Math.min(nObjects, 100);
for (int i = 0; i < warmupLoops; i++) {
testNewOperator(nObjects, objects);
testNewInstance(nObjects, objects);
}

System.gc();

// using new
System.out.println("Testing 'new'...");
long newTime = testNewOperator(nObjects, objects);
System.out.println("Took " + (newTime / 1000000f) + "ms to create " +
nObjects + " objects via 'new' (" +
(nObjects / (newTime / 1000000f)) +
" objects per ms)");
System.gc();
// using newInstance() on class
System.out.println("Testing 'newInstance()'...");
long niTime = testNewInstance(nObjects, objects);
System.out.println("Took " + (niTime / 1000000f) + "ms to create " +
nObjects + " objects via reflections (" +
(nObjects / (niTime / 1000000f)) +
" objects per ms)");
// ratio
System.out.println("'new' is " + (niTime / (float) newTime) +
" times faster than 'newInstance()'.");
}

private static long testNewInstance(int nObjects, Object[] objects)
throws Exception {
long start = System.nanoTime();
for (int i = 0; i < nObjects; i++) {
objects[i] = Object.class.newInstance();
}
return System.nanoTime() - start;
}

private static long testNewOperator(int nObjects, Object[] objects) {
long start = System.nanoTime();
for (int i = 0; i < nObjects; i++) {
objects[i] = new Object();
}
return System.nanoTime() - start;
}
}

Running this with -Xms512m -Xmx512m* yields the following result:

Testing 'new'...
Took 7.610116ms to create 1000000 objects via 'new' (131404.05 objects per ms)
Testing 'newInstance()'...
Took 184.72641ms to create 1000000 objects via reflections (5413.41 objects per ms)
'new' is 24.273798 times faster than 'newInstance()'.

Nearly 25x slower. If you lower the value of nObjects the difference gets smaller, though.
Testing 'new'...
Took 0.002794ms to create 100 objects via 'new' (35790.98 objects per ms)
Testing 'newInstance()'...
Took 0.021581ms to create 100 objects via reflections (4633.7056 objects per ms)
'new' is 7.7240515 times faster than 'newInstance()'.

Adding a -server flag to the VM parameters did the trick, though.
Testing 'new'...
Took 8.862299ms to create 1000000 objects via 'new' (112837.54 objects per ms)
Testing 'newInstance()'...
Took 13.91287ms to create 1000000 objects via reflections (71875.88 objects per ms)
'new' is 1.5698942 times faster than 'newInstance()'.

And for 100 object instantiations:
Testing 'new'...
Took 0.002864ms to create 100 objects via 'new' (34916.20 objects per ms)
Testing 'newInstance()'...
Took 0.006007ms to create 100 objects via reflections (16647.24 objects per ms)
'new' is 2.0974162 times faster than 'newInstance()'.

When the JIT magic kicks in, you get some SERIOUS improvements.
* NOTE: 512m to avoid garbage collection interference. You can run with -XX:+PrintGCDetails to ensure that the GC isn’t acting during the instantiation loops. You should see two full GC passages though, because of lines 14 and 23.
I did run the tests a dozen times for each test; the outputs posted fall within the averages.
Tip of the day: Even though I got far better results after introducing the warmup phase, I still suggest you use the good ol’ Factory pattern. Unless you’re creating a few dozen instances in a non-critical zones of your code, the factory is the way to go, as newInstance() can never (?) get as fast as new.


Monday, 14 March 2011

Working with Arrays using reflections in java

The Array (in the API reference documentation)class provides methods that allow you to dynamically create and access arrays. You'll learn how to use these methods in this lesson.

Identifying Arrays


This section shows you how to determine if an object really is an array.

Retrieving Component Types


If you want to find out the component type of an array, you'll want to check out the programming example in this section.

Creating Arrays


This section shows you how simple it is to create arrays at run time.

Getting and Setting Element Values


Even if you don't know the name of an array until run time, you can examine or modify the values of its elements. This section shows you how.

Type Descriptors in reflections

Field and Method types are represented, in a special notation, by a string. This notation is described below.

Primitive Types

Primitive types are represented by one of the following characters:
byteB
charC
doubleD
floatF
intI
longJ
shortS
booleanZ
For instance, an integer field would have a descriptor of "I".

Classes

Classes are indicated by an 'L', followed by the path to the class name, then a semi-colon to mark the end of the class name.
For instance, a String field would have a descriptor of "Ljava/lang/String;"

Arrays

Arrays are indicated with a '[' character.
For instance an array of Integers would have a descriptor of "[I".
Multi-dimensional arrays simply have extra '[' characters. For instance, "[[I".

Field Descriptors

A field has just one type, described in a string in the above notation. e.g. "I", or "Ljava/lang/String".

Method Descriptors

Because methods involve several types - the arguments and the return type - their type descriptor notation is slightly different. The argument types are at the start of the string inside brackets, concatenated together. Note that the type descriptors are concatenated without any separator character. The return type is after the closing bracket.
For instance, "int someMethod(long lValue, boolean bRefresh);" would have a descriptor of "(JZ)I". 

Attributes

Both the field_info table and the method_info table include a list of attributes. Each attribute starts with the index of a CONSTANT_Utf8 (2 bytes) and then the length of the following data (4 bytes). The structure of the following data depends on the particular attribute type. This allows new or custom attributes to be included in the class file without disrupting the existing structure, and without requiring recognition in the JVM specification. Any unrecognised attribute types will simply be ignored.
Attributes can contain sub-attributes. For instance, the code attribute can contain a LineNumberTable attribut
Here are some possible attributes:
CodeDetails, including bytecode, of a method's code.
ConstantValueUsed by 'final' fields
ExceptionsExceptions thrown by a method.
InnerClassesA class's inner classes.
LineNumberTableDebugging information
LocalVariableTableDebugging information.
SourceFileSource file name.
SyntheticShows that the field or method was generated by the compiler.

Code attribute

The Code attribute is used by the method_info table. It is where you will find the actual bytecodes (opcodes an operands) of the method's classes.
The attributes has the following structure:

Length (number of bytes)Description
max_stack2Size of stack required by the method's code.
max_locals2Number of local variables required by the method's code.
code_length2
codecode_lengthThe method's executable bytecodes
exception_table_length2
exception_tablevariesThe exceptions which the method can throw.
attributes_count2
attributesvariese.g. LineNumberTable
Each exception table entry has the following structure, each describing one exception catch:

Length (number of bytes)Description
start_pc2Offset of start of try/catch range.
end_pc2Offset of end of try/catch range.
handler_pc2Offset of start of exception handler code.
catch_type2Type of exception handled.
These entries for the Code attribute will probably only make sense to you if you are familiar with the rest of the JVM specification.
 source: http://www.murrayc.com/learning/java/java_classfileformat.shtml

Reflections (toc or index)

Before we being reflections we should note the following:

Note of caution for reflection
Now we can proceed further.

Examining Classes

Following is required to examine a class:


  • Retrieving Class Objects
    First things first. Before you can find out anything about a class, you must first retrieve its corresponding Class object.

  • Getting the Class Name
    It's easy to find out the name of a Class object. All you have to do is invoke the getName method.



  • Discovering Class Modifiers
    This section shows you the methods you need to call to find out what modifiers a particular class has.



  • Finding Superclasses
    In this section you'll learn how to retrieve all of the Class objects for the ancestors of a given class.



  • Identifying the Interfaces Implemented by a Class
    If you want to find out what interfaces a class implements, then check out this section.



  • Examining Interfaces
    In this section you'll learn how to tell if a Class object represents an interface or a class. You'll also get some tips on how to get more information about an interface.



  • Identifying Class Fields
    This section shows you how to discover what fields belong to a class, and how to find out more about these fields by accessing Field objects.



  • Discovering Class Constructors
    This section, which introduces the Constructor class, explains how to get information about a class's contructors.



  • Obtaining Method Information
    To find out about a class's methods, you need to retrieve the correspondingMethod objects. This section shows you how to do this.


  • Manipulating Objects

    Software development tools, such as GUI builders and debuggers, need to manipulate objects at run time. For example, a GUI builder may allow the end-user to select a Button from a menu of components, create the Buttonobject, and then click the Button while running the application within the GUI builder. If you're in the business of creating software development tools, you'll want to take advantage of the reflection API features described in this lesson.
    • Creating Objects
      How can you create an object if you don't know its class name until run time? You'll find the answer in this section.
    • Getting Field Values
      In this section you'll learn how to get the values of an object's fields, even if you don't know the name of the object, or even its class, until run time.
    • Setting Field Values
      Not only can you get field values at run time, you can also set them. This section shows you how.
    • Invoking Methods
      This section shows you how to dynamically invoke methods. Given an object, you can find out what methods its class defines, and then invoke the methods.


    Creating Objects


    Working with Arrays

    Summary of Classes

    Thursday, 24 February 2011

    Cost associated with reflections in java

    Reflection is v.powerful and useful, but comes at some cost:
    • You lose all the benefits of compile-time type checking, including exception checking. If a program attempts to invoke a nonexistent or inaccessible method reflectively, it will fail at run time unless you've taken special precautions.
    • The code required to perform reflective access is clumsy and verbose. It is tedious to write and difficult to read.
    • Performance suffers

    Sunday, 26 September 2010

    Invoking Methods

      Suppose you are writing a debugger which allows the user to select and then invoke methods during a debugging session. Since you don't know at compile time which methods the user will invoke, you cannot hardcode the method name in your source code. Instead, you must follow these steps:
    1. Create a Class object that corresponds to the object whose method you want to invoke. See Retrieving Class Objects for more information.
    2. Create a Method object by invoking getMethod upon the 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 parameter of the method you want to invoke. For more information on retrieving Method objects, see Obtaining Method Information
    3. 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.
    The sample program that follows shows you how to invoke a method dynamically. The program retrieves the Method object for the String.concat method and then uses invoke to concatenate two String objects.
    import java.lang.reflect.*;

    class SampleInvoke {

    public static void main(String[] args) {
    String firstWord = "Hello ";
    String secondWord = "everybody.";
    String bothWords = append(firstWord, secondWord);
    System.out.println(bothWords);
    }

    public static 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};
    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;
    }
    }
    The output of the preceding program is:
    Hello everybody.


    Summary of Classes

    The following table summarizes the classes that comprise the reflection API. The Class and Object classes are in the java.lang package. The other classes are contained in the java.lang.reflect package.
    ClassDescription
    ArrayProvides static methods to dynamically create and access arrays.
    ClassRepresents, or reflects, classes and interfaces.
    ConstructorProvides information about, and access to, a constructor for a class.
    Allows you to instantiate a class dynamically.
    FieldProvides information about, and dynamic access to, a field of a class
    or an interface.
    MethodProvides information about, and access to, a single method on a class
    or interface. Allows you to invoke the method dynamically.
    ModifierProvides static methods and constants that allow you to get
    information about the access modifiers of a class and its members.
    ObjectProvides the getClass method.
    So on the class basis:
    For each of these three types of class components -- constructors, fields, and methods -- see here for more--http://www.ibm.com/developerworks/library/j-dyn0603/

    The Java Class File Format

    Introduction

    Compiled binary executables for different platforms usually differ not only in the instruction set, libraries, and APIs at which they are aimed, but also by the file format which is used to represent the program code. For instance, Windows uses the COFF file format, while Linux uses the ELF file format. Because Java aims at binary compatibility, it needs a universal file format for its programs - the Class File format.
    The class file consists of some data of fixed length and lots of data of variable length and quantity, often nested inside other data of variable length. Therefore it is generally necessary to parse the whole file to read any one piece of data, because you will not know where that data is until you have worked your way through all the data before it. The JVM would just read the class file once and either store the data from the class file temporarily in a more easily accessed (but larger) format, or just remember where everything is in the class file. For this reason, a surprisingly large amount of the code of any JVM will be concerned with the interpretation, mapping, and possibly caching of this class file format.
    Please note that this document is just an overview. The actual Class File format description is in the 'Java Virtual Machine Specification' which can be found online here, or in printed form here.

    The Start

    The Class file starts with the following bytes:
    Length (number of bytes)Example
    magic40xCAFEBABE
    minor_version20x0003
    major_version20x002D
    The 'magic' bytes are always set to 0xCAFEBABE and are simply a way for the JVM to check that it has loaded a class file rather than some other set of bytes.
    The version bytes identify the version of the Class File format which this file conforms to. Obviously a JVM would have trouble reading a class file format which was defined after that JVM was written. Each new version of the JVM specification generally says what range of Class File versions it should be able to process.

    Constant Pool

    This major_version is followed by the constant_pool_count (2 bytes), and the constant_pool table.
    The constant_pool table consists of several entries which can be of various types, and therefore of variable length. There are constant_pool_count - 1 entries, and each entries is referred to by its 1-indexed position in the table. Therefore, the first item is referred to as Constant Pool item 1. An index into the Constant Pool table can be store in 2 bytes.
    Each entry can be one of the following, and is identified by the tag byte at the start of the entry.
    TagContents
    CONSTANT_Class7The name of a class 
    CONSTANT_Fieldref 9The name and type of a Field, and the class of which it is a member.
    CONSTANT_Methodref 10The name and type of a Method, and the class of which it is a member.
    CONSTANT_InterfaceMethodref 11The name and type of a Interface Method, and the Interface of which it is a member.
    CONSTANT_String8The index of a CONSTANT_Utf8 entry.
    CONSTANT_Integer34 bytes representing a Java integer.
    CONSTANT_Float 44 bytes representing a Java float.
    CONSTANT_Long58 bytes representing a Java long.
    CONSTANT_Double68 bytes representing a Java double.
    CONSTANT_NameAndType12The Name and Type entry for a field, method, or interface.
    CONSTANT_Utf812 bytes for the length, then a string in Utf8 (Unicode) format.
    Note that the primitive types, such as CONSTANT_Integer, are stored in big-endian format, with the most significant bits first. This is the most obvious and intuitive way of storing values, but some processors (in particular, Intel x86 processors) use values in little-endian format, so the JVM may need to manipulate these bytes to get the data into the correct form.
    Many of these entries refer to other entries, but they generally end up referring to one or more Utf8 entries.
    For instance, here is are the levels of containment for a CONSTANT_Fieldref entry:
    CONSTANT_Fieldref
        index to a CONSTANT_Class entry
            index to a CONSTANT_Utf8 entry
        index to a CONSTANT_NameAndType entry
            index to a CONSTANT_Utf8 entry (name)
            index to a CONSTANT_Utf8 entry (type descriptor)
    Note that simple text names are used to identify entities such as classes, fields, and methods. This greatly simplifies the task of linking them together both externally and internally.

    The Middle Bit

    access_flags (2 bytes)

    This shows provide information about the class, by ORing the following flags together:
    • ACC_PUBLIC
    • ACC_FINAL
    • ACC_SUPER
    • ACC_INTERFACE
    • ACC_ABSTRACT

    this_class

    These 2 bytes are an index to a CONSTANT_Class entry in the constant_pool, which should provide the name of this class.

    super_class

    Like this_class, but provides the name of the class's parent class. Remember that Java only has single-inheritance, so there can not be more than one immediate base class.

    Interfaces

    2 bytes for the interfaces_count, and then a table of CONSTANT_InterfaceRef indexes, showing which interfaces this class 'implements' or 'extends'..

    Fields

    After the interfaces table, there are 2 bytes for the fields_count, followed by a table of field_info tables.
    Each field_info table contains the following information:
    Length (number of bytes)Description
    access_flags2e.g. ACC_PUBLIC, ACC_PRIVATE, etc
    name_index2Index of a CONSTANT_Utf8
    descriptor_index2Index of a CONSTANT_Utf8 (see type descriptors)
    attributes_count2
    attributesvariese.g. Constant Value. (see attributes)

    Methods

     After the fields table, there are 2 bytes for the methods_count, followed by a table of method_info tables. This has the same entries as the field_info table, with the following differences:
    • The access_flags are slightly different.
    • The descriptor has a slightly different format (see type descriptors)
    • A different set attributes are included in the attributes table - most importantly the 'code' attribute which contains the Java bytecode for the method. (see attributes)

    Type Descriptors

    Field and Method types are represented, in a special notation, by a string. This notation is described below.

    Primitive Types

    Primitive types are represented by one of the following characters:
    byteB
    charC
    doubleD
    floatF
    intI
    longJ
    shortS
    booleanZ
    For instance, an integer field would have a descriptor of "I".

    Classes

    Classes are indicated by an 'L', followed by the path to the class name, then a semi-colon to mark the end of the class name.
    For instance, a String field would have a descriptor of "Ljava/lang/String;"

    Arrays

    Arrays are indicated with a '[' character.
    For instance an array of Integers would have a descriptor of "[I".
    Multi-dimensional arrays simply have extra '[' characters. For instance, "[[I".

    Field Descriptors

    A field has just one type, described in a string in the above notation. e.g. "I", or "Ljava/lang/String".

    Method Descriptors

    Because methods involve several types - the arguments and the return type - their type descriptor notation is slightly different. The argument types are at the start of the string inside brackets, concatenated together. Note that the type descriptors are concatenated without any separator character. The return type is after the closing bracket.
    For instance, "int someMethod(long lValue, boolean bRefresh);" would have a descriptor of "(JZ)I". 

    Attributes

    Both the field_info table and the method_info table include a list of attributes. Each attribute starts with the index of a CONSTANT_Utf8 (2 bytes) and then the length of the following data (4 bytes). The structure of the following data depends on the particular attribute type. This allows new or custom attributes to be included in the class file without disrupting the existing structure, and without requiring recognition in the JVM specification. Any unrecognised attribute types will simply be ignored.
    Attributes can contain sub-attributes. For instance, the code attribute can contain a LineNumberTable attribut
    Here are some possible attributes:
    CodeDetails, including bytecode, of a method's code.
    ConstantValueUsed by 'final' fields
    ExceptionsExceptions thrown by a method.
    InnerClassesA class's inner classes.
    LineNumberTableDebugging information
    LocalVariableTableDebugging information.
    SourceFileSource file name.
    SyntheticShows that the field or method was generated by the compiler.

    Code attribute

    The Code attribute is used by the method_info table. It is where you will find the actual bytecodes (opcodes an operands) of the method's classes.
    The attributes has the following structure:
    Length (number of bytes)Description
    max_stack2Size of stack required by the method's code.
    max_locals2Number of local variables required by the method's code.
    code_length2
    codecode_lengthThe method's executable bytecodes
    exception_table_length2
    exception_tablevariesThe exceptions which the method can throw.
    attributes_count2
    attributesvariese.g. LineNumberTable
    Each exception table entry has the following structure, each describing one exception catch:
    Length (number of bytes)Description
    start_pc2Offset of start of try/catch range.
    end_pc2Offset of end of try/catch range.
    handler_pc2Offset of start of exception handler code.
    catch_type2Type of exception handled.
    These entries for the Code attribute will probably only make sense to you if you are familiar with the rest of the JVM specification.
    source: http://www.murrayc.com/learning/java/java_classfileformat.shtml

    Thursday, 23 September 2010

    Creating class instance using Constructors that Have Arguments

    To create an object with a constructor that has arguments, you invoke the newInstance method upon a Constructor  object, not a Class object. This technique involves several steps:
    1. Create a Class object for the object you want to create.
    2. Create a Constructor object by invoking getConstructor upon the Class object. The getConstructor method has one parameter: an array of Class objects that correspond to the constructor's parameters.
    3. Create the object by invoking newInstance upon the Constructor object. The newInstance method has one parameter: an Object array whose elements are the argument values being passed to the constructor.
    The sample program that follows creates a Rectangle with the constructor that accepts two integers as parameters. Invoking newInstance upon this constructor is analagous to this statement:
    Rectangle rectangle = new Rectangle(12, 34);
    This constructor's arguments are primitive types, but the argument values passed to newInstance must be objects. Therefore, each of the primitive int types is wrapped in an Integer object. The sample program hardcodes the argument passed to the getConstructor method. In a real-life application such as a debugger, you would probably let the user select the constructor. To verify the user's selection, you could use the methods described in Discovering Class Constructors.
    The source code for the sample program is:
    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;
    }
    }
    The sample program prints a description of the constructor and the object that it creates:
    Constructor: public java.awt.Rectangle(int,int)
    Object: java.awt.Rectangle[x=0,y=0,width=12,height=34]

    Creating class instance using No-Argument Constructors using reflection in java

    If you need to create an object with the no-argument constructor, you can invoke the newInstance method upon a Class object. The newInstance method throws a NoSuchMethodException if the class does not have a no-argument constructor. For more information on working with Constructor objects, see Discovering Class Constructors.
    The following sample program creates an instance of the Rectangle class using the no-argument constructor by calling the newInstance method:
    import java.lang.reflect.*;
    import java.awt.*;

    class SampleNoArg {

    public static void main(String[] args) {
    Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
    System.out.println(r.toString());
    }

    static Object createObject(String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (InstantiationException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    } catch (ClassNotFoundException e) {
    System.out.println(e);
    }
    return object;
    }
    }
    The output of the preceding program is:
    java.awt.Rectangle[x=0,y=0,width=0,height=0]

    Wednesday, 22 September 2010

    Getting and Setting Element Values using reflection in java

    In most programs, to access array elements you merely use an assignment expression:
    int[10] codes; 
    codes[3] = 22;
    aValue = codes[3];
    This technique will not work if you don't know the name of the array until run time. Fortunately, you can use the Array class set and get methods to access array elements when the name of the array is unknown at compile time. In addition to get and set, the Array class has specialized methods that work with specific primitive types. For example, the value parameter of setInt is an int, and the object returned by getBoolean is a wrapper for a boolean type.
    The sample program that follows uses the set and get methods to copy the contents of one array to another.
    import java.lang.reflect.*;

    class SampleGetArray {

    public static void main(String[] args) {
    int[] sourceInts = {12, 78};
    int[] destInts = new int[2];
    copyArray(sourceInts, destInts);
    String[] sourceStrgs = {"Hello ", "there ", "everybody"};
    String[] destStrgs = new String[3];
    copyArray(sourceStrgs, destStrgs);
    }

    public static void copyArray(Object source, Object dest) {
    for (int i = 0; i < Array.getLength(source); i++) {
    Array.set(dest, i, Array.get(source, i));
    System.out.println(Array.get(dest, i));
    }
    }
    }
    The output of the sample program is:
    12
    78
    Hello
    there
    everybody

    Identifying Arrays using reflections

    If you aren't certain that a particular object is an array, you can check it with the Class.isArray method. Let's take a look at an example.
    The sample program that follows prints the names of the arrays which are encapsulated in an object. The program performs these steps:
    1. It retrieves the Class object that represents the target object.
    2. It gets the Field objects for the Class object retrieved in the preceding step.
    3. For each Field object, the program gets a corresponding Class object by invoking the getType method.
    4. To verify that the Class object retrieved in the preceding step represents an array, the program invokes the isArray method.
    Here's the source code for the sample program:
    import java.lang.reflect.*;
    import java.awt.*;

    class SampleArray {

    public static void main(String[] args) {
    KeyPad target = new KeyPad();
    printArrayNames(target);
    }

    static void printArrayNames(Object target) {
    Class targetClass = target.getClass();
    Field[] publicFields = targetClass.getFields();
    for (int i = 0; i < publicFields.length; i++) {
    String fieldName = publicFields[i].getName();
    Class typeClass = publicFields[i].getType();
    String fieldType = typeClass.getName();
    if (typeClass.isArray()) {
    System.out.println("Name: " + fieldName +
    ", Type: " + fieldType);
    }
    }
    }
    }

    class KeyPad {

    public boolean alive;
    public Button power;
    public Button[] letters;
    public int[] codes;
    public TextField[] rows;
    public boolean[] states;
    }
    The output of the sample program follows. Note that the left bracket indicates that the object is an array.
    Name: letters, Type: [Ljava.awt.Button;
    Name: codes, Type: [I
    Name: rows, Type: [Ljava.awt.TextField;
    Name: states, Type: [Z

    Creating Arrays in java using reflections

    If you are writing a development tool such as an application builder, you may want to allow the end-user to create arrays at run time. Your program can provide this capability by invoking the Array.newInstance method.
    The following sample program uses the newInstance method to create a copy of an array which is twice the size of the original array. The newInstance method accepts as arguments the length and component type of the new array. The source code is as follows:
    import java.lang.reflect.*;

    class SampleCreateArray {

    public static void main(String[] args) {
    int[] originalArray = {55, 66};
    int[] biggerArray = (int[]) doubleArray(originalArray);
    System.out.println("originalArray:");
    for (int k = 0; k < Array.getLength(originalArray); k++)
    System.out.println(originalArray[k]);
    System.out.println("biggerArray:");
    for (int k = 0; k < Array.getLength(biggerArray); k++)
    System.out.println(biggerArray[k]);
    }

    static Object doubleArray(Object source) {
    int sourceLength = Array.getLength(source);
    Class arrayClass = source.getClass();
    Class componentClass = arrayClass.getComponentType();
    Object result = Array.newInstance(componentClass, sourceLength * 2);
    System.arraycopy(source, 0, result, 0, sourceLength);
    return result;
    }
    }

    The output of the preceding program is:
    originalArray:
    55
    66
    biggerArray:
    55
    66
    0
    0
    You can also use the newInstance method to create multi-dimensional arrays. In this case, the parameters of the method are the component type and an array of int types representing the dimensions of the new array. The next sample program shows how to use newInstance to create multi-dimensional arrays:
    import java.lang.reflect.*;

    class SampleMultiArray {

    public static void main(String[] args) {

    // The oneDimA and oneDimB objects are one
    // dimensional int arrays with 5 elements.

    int[] dim1 = {5};
    int[] oneDimA = (int[]) Array.newInstance(int.class, dim1);
    int[] oneDimB = (int[]) Array.newInstance(int.class, 5);

    // The twoDimStr object is a 5 X 10 array of String objects.

    int[] dimStr = {5, 10};
    String[][] twoDimStr =
    (String[][]) Array.newInstance(String.class,dimStr);

    // The twoDimA object is an array of 12 int arrays. The tail
    // dimension is not defined. It is equivalent to the array
    // created as follows:
    // int[][] ints = new int[12][];

    int[] dimA = {12};
    int[][] twoDimA = (int[][]) Array.newInstance(int[].class, dimA);
    }
    }

    Retrieving Component Types using reflection in java

    The component type is the type of an array's elements. For example, the component type of the arrowKeys array in the following line of code is Button:
    Button[] arrowKeys = new Button[4];
    The component type of a multi-dimensional array is an array. In the next line of code, the component type of the array named matrix is int[]:
    int[][] matrix = new int[100][100];
    By invoking the getComponentType method against the Class object that represents an array, you can retrieve the component type of the array's elements. The sample program that follows invokes the getComponentType method and prints out the class name of each array's component type.
    import java.lang.reflect.*;
    import java.awt.*;

    class SampleComponent {

    public static void main(String[] args) {
    int[] ints = new int[2];
    Button[] buttons = new Button[6];
    String[][] twoDim = new String[4][5];

    printComponentType(ints);
    printComponentType(buttons);
    printComponentType(twoDim);
    }

    static void printComponentType(Object array) {
    Class arrayClass = array.getClass();
    String arrayName = arrayClass.getName();
    Class componentClass = arrayClass.getComponentType();
    String componentName = componentClass.getName();
    System.out.println("Array: " + arrayName +
    ", Component: " + componentName);
    }
    }

    The output of the sample program is:
    Array: [I, Component: int
    Array: [Ljava.awt.Button;, Component: java.awt.Button
    Array: [[Ljava.lang.String;, Component: [Ljava.lang.String;

    Setting Field Values using reflection in java

    Some debuggers allow users to change field values during a debugging session. If you are writing a tool that has this capability, you must call the one of the Field class's set methods. To modify the value of a field, perform the following steps:
    1. Create a Class object. For more information, see Retrieving Class Objects.
    2. Create a Field object by invoking getField upon the Class object. Identifying Class Fields shows you how.
    3. Invoke the appropriate set method upon 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, then 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.
    The sample program that follows modifies the width field of a Rectangle object by invoking the set method. Since the width is a primitive type, an int, the value passed by set is an Integer, which is an object wrapper.
    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());
    }

    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);
    }
    }
    }
    The output of the sample program verifies that the width changed from 100 to 300:
    original: java.awt.Rectangle[x=0,y=0,width=100,height=20]
    modified: java.awt.Rectangle[x=0,y=0,width=300,height=20]

    Creating Objects using reflection in java

    The simplest way to create an object in the Java programming language is to use the new operator:
    Rectangle r = new Rectangle();
    This technique is adequate for nearly all applications, because usually you know the class of the object at compile time. However, if you are writing development tools, you may not know the class of an object until run time. For example, a GUI builder might allow the user to drag and drop a variety of GUI components onto the page being designed. In this situation, you may be tempted to create the GUI components as follows:
    String className; 

    // . . . load className from the user interface

    Object o = new (className); // WRONG!
    The preceding statement is invalid because the new operator does not accept arguments. Fortunately, with the reflection API you can create an object whose class is unknown until run time. The method you invoke to create an object dynamically depends on whether or not the constructor you want to use has arguments:


    Getting Field Values using reflection in java

    If you are writing a development tool such as a debugger, you must be able to obtain field values. This is a three-step process:
    1. Create a Class object. Retrieving Class Objects shows you how to do this.
    2. Create a Field object by invoking getField upon the Class object. For more information, see Identifying Class Fields.
    3. Invoke one of the get methods upon the Field object.
    The Field (in the API reference documentation)class has specialized methods for getting the values of primitive types. For example, the getInt method returns the contents as an int value, getFloat returns a float, and so forth. If an object is stored in the field instead of a primitive, then use the get method to retrieve the object. The following sample program demonstrates the three steps listed previously. This program gets the value of the height field from a Rectangle object. Because the height is a primitive type (int), the object returned by the get method is a wrapper object (Integer).
    In the sample program, the name of the height field is known at compile time. However, in a development tool such as a GUI builder, the field name might not be known until run time. To find out what fields belong to a class, you can use the techniques described in Identifying Class Fields.
    Here is the source code for the sample program:
    import java.lang.reflect.*;
    import java.awt.*;

    class SampleGet {

    public static void main(String[] args) {
    Rectangle r = new Rectangle(100, 325);
    printHeight(r);

    }

    static void printHeight(Rectangle r) {
    Field heightField;
    Integer heightValue;
    Class c = r.getClass();
    try {
    heightField = c.getField("height");
    heightValue = (Integer) heightField.get(r);
    System.out.println("Height: " + heightValue.toString());
    } catch (NoSuchFieldException e) {
    System.out.println(e);
    } catch (SecurityException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    }
    }
    }
    The output of the sample program verifies the value of the height field:
    Height: 325

    Obtaining Method Information

    To find out what methods belong to a class, invoke the method named getMethods. The array returned by getMethods contains Method objects. You can use a Method object to uncover a method's name, return type, parameter types, set of modifiers, and set of throwable exceptions. All of this information would be useful if you were writing a class browser or a debugger. With Method.invoke, you can even call the method itself. To see how to do this, see Invoking Methods. The following sample program prints the name, return type, and parameter types of every public method in the Polygon class. The program performs these tasks:
    1. It retrieves an array of Method objects from the Class object by calling getMethods.
    2. For every element in the Method array, the program:
      1. retrieves the method name by calling getName
      2. gets the return type by invoking getReturnType
      3. creates an array of Class objects by invoking getParameterTypes
    3. The array of Class objects created in the preceding step represents the parameters of the method. To retrieve the class name for every one of these parameters, the program invokes getName against each Class object in the array.
    Not many lines of source code are required to accomplish these tasks:
    import java.lang.reflect.*;
    import java.awt.*;

    class SampleMethod {

    public static void main(String[] args) {
    Polygon p = new Polygon();
    showMethods(p);
    }

    static void showMethods(Object o) {
    Class c = o.getClass();
    Method[] theMethods = c.getMethods();
    for (int i = 0; i < theMethods.length; i++) {
    String methodString = theMethods[i].getName();
    System.out.println("Name: " + methodString);
    String returnString =
    theMethods[i].getReturnType().getName()
    ;
    System.out.println(" Return Type: " + returnString);
    Class[] parameterTypes = theMethods[i].getParameterTypes();
    System.out.print(" Parameter Types:");
    for (int k = 0; k < parameterTypes.length; k ++) {
    String parameterString = parameterTypes[k].getName();
    System.out.print(" " + parameterString);
    }
    System.out.println();
    }
    }
    }
    An abbreviated version of the output generated by the sample program is as follows:
    Name: equals
    Return Type: boolean
    Parameter Types: java.lang.Object
    Name: getClass
    Return Type: java.lang.Class
    Parameter Types:
    Name: hashCode
    Return Type: int
    Parameter Types:
    .
    .
    .
    Name: intersects
    Return Type: boolean
    Parameter Types: double double double double
    Name: intersects
    Return Type: boolean
    Parameter Types: java.awt.geom.Rectangle2D
    Name: translate
    Return Type: void
    Parameter Types: int int

    Manipulating Objects

    Software development tools, such as GUI builders and debuggers, need to manipulate objects at run time. 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. If you're in the business of creating software development tools, you'll want to take advantage of the reflection API features described in this lesson.

    Creating Objects

    How can you create an object if you don't know its class name until run time? You'll find the answer in this section.

    Getting Field Values

    In this section you'll learn how to get the values of an object's fields, even if you don't know the name of the object, or even its class, until run time.

    Setting Field Values

             Not only can you get field values at run time, you can also set them. This section shows you how.

    Invoking Methods

            This section shows you how to dynamically invoke methods. Given an object, you can find out what methods its class defines, and then invoke the methods.

    Discovering Class Constructors using reflection

    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. Using the methods provided by the Constructor class, you can 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. You'll learn how to invoke Constructor.newInstance in Manipulating Objects.
    The sample program that follows prints out the parameter types for each constructor in the Rectangle class. The program performs the following steps:
    1. It retrieves an array of Constructor objects from the Class object by calling getConstructors.
    2. For every element in the Constructor array, it creates an array of Class objects by invoking getParameterTypes. The Class objects in the array represent the parameters of the constructor.
    3. By calling getName, the program fetches the class name for every parameter in the Class array created in the preceding step.
    It's not as complicated as it sounds. Here's the source code for the sample program:
    import java.lang.reflect.*;
    import java.awt.*;

    class SampleConstructor {

    public static void main(String[] args) {
    Rectangle r = new Rectangle();
    showConstructors(r);
    }

    static void showConstructors(Object o) {
    Class c = o.getClass();
    Constructor[] theConstructors = c.getConstructors();
    for (int i = 0; i < theConstructors.length; i++) {
    System.out.print("( ");
    Class[] parameterTypes =
    theConstructors[i].getParameterTypes();
    for (int k = 0; k < parameterTypes.length; k ++) {
    String parameterString = parameterTypes[k].getName();
    System.out.print(parameterString + " ");
    }
    System.out.println(")");
    }
    }
    }
    In the first line of output generated by the sample program, no parameter types appear because that particular Constructor object represents a no-argument constructor. In subsequent lines, the parameters listed are either int types or fully-qualified object names. The output of the sample program is as follows:
    ( )
    ( int int )
    ( int int int int )
    ( java.awt.Dimension )
    ( java.awt.Point )
    ( java.awt.Point java.awt.Dimension )
    ( java.awt.Rectangle )