Results 1 to 5 of 5

Thread: How to use Reflection in Java

  1. #1
    Join Date
    Jul 2010
    Posts
    118

    How to use Reflection in Java

    Here is the Tutorial on reflection in Java. We'll see how to get the constructors, methods and fields of a class using reflection. We will also see how to execute a method, any manufacturer of a class. For a beginner in Java, this guide will not be very useful, although simple, reflection may seem somewhat superfluous or unnecessary, but with a little experience in major IT projects, reflection can make many services. Small note on the code presented in this tutorial: the code is planned for Java 6 (it is still very easy to make it compatible with a lower version, in case of difficulty, ask me).


    What is Reflection?

    In computer programming, reflection is the ability of a program to examine and possibly modify its high level of internal structures (eg objects) at runtime. To be more clear thinking is the opportunity the program can access or change the structure of an object during program execution. Structure of an object by means everything is property, class, function etc. .. In general, in languages "conventional" (C or C + + for example), the structure of an object is only known at compile time, that is to say that it is not possible to execution, to know "what in the belly" type of object. Java implements reflection. It does, however, only the ability to access structures and not change them. Thus, implementation of a Java program, it is quite possible to know the precise structure of any object and can interact with (ie for example execute any function of the object) but you can not, for example, add a function or a field to the object. The structure of an object in Java is characterized by a class that contains constructors, methods (or functions) and finally fields. Reflection in Java allows at run time the definition of any object as we had planned.


    Implementation

    The java.lang.reflect package is devoted to reflection. As seen above, the structure of a Java object is characterized by a class that contains constructors, methods (or functions) and finally fields. The characteristics of the object are represented formally by a class package for consideration:
    • Class package - Represents
    • Class - A class.
    • Method - A method of a class
    • Constructor - Constructor of a class
    • Field - A field of a class
    Note, to avoid remark comment Class not part of the package java.lang java.lang.reflect but nevertheless well Class participates in the mechanism of reflection. I have deliberately limited the list of classes of the package. The purpose of this tutorial is to give a first approach to thinking. Let it therefore to the reader to learn more detail, if it needs a little deeper. For example, across Method, we can know the name of the method, the parameters it takes, and the type of return value. I highly recommend you take a look at Package java.lang.reflect.

  2. #2
    Join Date
    Jul 2010
    Posts
    118

    Re: How to use Reflection in Java

    To understand, consider the following class:

    Code:
    public class Test1 
    
    { 
    
    private int unChamp2; 
    
    public Test () 3 
    
    { 
    
    } 
    
    
    public int method (String arg) 4 
    
    { 
    
    } 
    
    }
    The structure of the object test is the following:
    • 1: A Class representing the class Test
    • 2: A Field representing the field unChamp
    • 3: A Constructor representing the class constructor
    • 4: Method A representative method method
    To access the full structure of an object, everything is made from Class. To retrieve the class of an instance of an object, nothing more simple, a simple getClass on the object:
    Code:
    Class class = obj.getClass ();
    It is also possible to retrieve the class from a type of object. For example, for String:
    Code:
    Class class = String.class;
    From here, to recover (examples are developed below):
    • A method, use getMethod ()
    • A manufacturer, use GetConstructors ()
    • A field, use getField ()
    We saw above that the reflection was not only to access the structure of an object but also to interact with the object. Thus, you can call any method, construct an instance from a constructor or assign a value to a field. You'll understand that these operations are done from class Method, Constructor and Field. To create a new instance of an object, it uses the newInstance of Constructor. This function returns a new instance. Then, to call a method, it uses the Invoke Method. This feature allows you to execute the method on an instance of an object. Finally, to assign a value to a field, we use the function set Field. We will apply the concepts seen so far through several examples to better understand.

  3. #3
    Join Date
    Jul 2010
    Posts
    118

    Re: How to use Reflection in Java

    Examples of access to the structure of an object

    Through the examples below, we will learn how to use reflection to access the structure of any object. You'll see it's very simple.

    1. Retrieve the class of an object

    Obj is any object, the following code gives its Class. Do not forget that recovery is the starting point for all information of an object
    Code:
    Class class = obj.getClass ();
    It is also possible to recover the class of an instance of type String:
    Code:
    Class class = String.class;
    2. Retrieve method

    From the moment we have recovered, you can access the class methods. The following code provides all the methods of the class in a table.
    Code:
    import java.lang.reflect.Method; // line added at the beginning of class 
    
    Method methods [] = class.getMethods ();
    One method is identified by its signature that is its name and the list of parameter types. Note that the Java reflection can be traced back only methods of public visibility (unlike Csharp). Suppose we want the concat function that takes as parameter a string (String). The code is as follows:
    Code:
    Concat = class.getMethod ("concat", String.class);
    The first parameter is the getMethod method name being sought. Caution name is sensitive to capitalization. The following parameters are the types of function parameters. Here, we want the function concat with exactly one parameter of type String. If you try this code, your compiler may grumble about unhandled exceptions.

    Exceptions raised:

    When using getMethod, two exceptions are likely to be lifted. These exceptions are required to be managed so that the code above is correct.
    NoSuchMethodException: when the requested method is not found
    SecurityException: if your code is not allowed to retrieve the method
    Thus, the code above to complete it compiles is as follows:
    Code:
    try 
    
    { 
    
    Concat = class.getMethod ("concat", String.class); 
    
    } Catch (SecurityException e) 
    
    { 
    
    // Prb Security 
    
    e.printStackTrace (); 
    
    } Catch (NoSuchMethodException e) 
    
    { 
    
    // The method does not 
    
    e.printStackTrace (); 
    
    }
    3. Retrieve a manufacturer

    A manufacturer, in contrast to a method, not identified by name (since by definition, a manufacturer still bears the name of the class) but only by the type of its parameters. As for methods, note that Java reflection can be traced back only to manufacturers in public visibility. The principle remains the same as the Methods except that instead of using getMethod, use GetConstructors. For all manufacturers :
    Code:
    import java.lang.reflect.Constructor // add at the beginning of a file 
    
    Constructor [] constructors = class.getConstructors ();
    For retrieving a manufacturer in particular:
    Code:
    try 
    
    { 
    
    Constructor constructor = class.getConstructor (StringBuilder.class); 
    
    } Catch (SecurityException e) 
    
    { 
    
    // Prb Security 
    
    e.printStackTrace (); 
    
    } Catch (NoSuchMethodException e) 
    
    { 
    
    // The constructor does not exist 
    
    e.printStackTrace (); 
    
    }
    Note that the exceptions raised are the same as for getMethod.

    4. Retrieve a field
    To retrieve a field, use getField. It should also be noted that it retrieves only the fields visible in public. For all fields :
    Code:
    import java.lang.reflect.Field; 
    
    Field [] fields = class.getFields ();
    For a particular field:
    A field is uniquely identified by name. Suppose we want the name field of the object:
    Code:
    try 
    
    { 
    
    Class.getField Field field = ("name"); 
    
    } Catch (SecurityException e) 
    
    { 
    
    // Prb Security 
    
    e.printStackTrace (); 
    
    } Catch (e NoSuchFieldException) 
    
    { 
    
    // The field does not exist 
    
    e.printStackTrace (); 
    
    }
    When the field does not exist, it is the exception that is thrown NoSuchFieldException.

  4. #4
    Join Date
    Jul 2010
    Posts
    118

    Re: How to use Reflection in Java

    Examples of interactions with an object

    With the examples above, you see I do not lie to you, the reflection is very simple. It's fine to recover the methods and information, but it'll be even nicer if we could interact with any object! For example, calling any method or construct any instance. Once we have the Method, Constructor, and Field, it is even easier to perform operations on an object.

    1. Construct an instance from a Constructor

    From Constructor recovered on a type, it is very easy to construct an instance. This is done using the newInstance function. This function takes a list of constructor parameters. By repeating the builder recovered above, this constructor takes a StringBuilder, it is therefore imperative to him to pass a sentence under an exception:
    Code:
    try 
    
    { 
    
    Object Instance = constructeur.newInstance (new StringBuilder ()); 
    
    } Catch (IllegalArgumentException e) 
    
    { 
    
    // Number of arguments is not good 
    
    e.printStackTrace (); 
    
    } Catch (InstantiationException e) 
    
    { 
    
    // Class is abstract (instance of an abstract class can not) 
    
    e.printStackTrace (); 
    
    } Catch (IllegalAccessException e) 
    
    { 
    
    // Constructor is not accessible 
    
    e.printStackTrace (); 
    
    } Catch (InvocationTargetException e) 
    
    { 
    
    // The constructor threw an exception 
    
    e.printStackTrace (); 
    
    }
    NewInstance function will return the new instance of the type. The exceptions that can be thrown are:
    IllegalArgumentException: the number of arguments is not good or are the wrong size
    InstantiationException: if one tries to instantiate an abstract class (not in Java)
    IllegalAccessException: the constructor is not accessible (private visibility is, for example)
    InvocationTargetException: the constructor threw an exception

    2. Method Call

    From the Method object, we can execute the method on an instance of the object. We use the invoke function parameter that takes an instance of an object on which to execute the method and the list of method parameters. Taking the method recovered in the example above.
    Code:
    try 
    
    { 
    
    Object object = "hello"); 
    
    Concat.invoke Object result = (object, "everybody"); 
    
    } Catch (IllegalArgumentException e) 
    
    { 
    
    // Arguments passed to the method are not good 
    
    e.printStackTrace (); 
    
    } Catch (IllegalAccessException e) 
    
    { 
    
    // Function not available 
    
    e.printStackTrace (); 
    
    } Catch (InvocationTargetException e) 
    
    { 
    
    // Method threw an exception 
    
    e.printStackTrace (); 
    
    }
    If the method executed should return a value, that value is returned back to the call to invoke. The exceptions that can be thrown are:
    IllegalArgumentException: the number of arguments is not good or are the wrong size
    IllegalAccessException: the method is not accessible (for example, is private)
    InvocationTargetException: the method threw an exception

    3. Assigning a value to a field

    To assign a value to a field in an instance of an object, use the set method Field of the field to edit.
    Code:
    try 
    
    { 
    
    champ.set (object, "tutorial"); 
    
    } Catch (IllegalArgumentException e) 
    
    { 
    
    // The parameter passed is invalid (not the right type for example) 
    
    e.printStackTrace (); 
    
    } Catch (IllegalAccessException e) 
    
    { 
    
    // Function not available 
    
    e.printStackTrace (); 
    
    }
    The exceptions that can be thrown are:
    IllegalArgumentException: value field to be defined is not the right type
    IllegalAccessException: the field is not accessible (for example, is set to private)

    4. Reading a field value

    Similarly, one can read the value of a field using the get function of Field.
    Code:
    try 
    
    { 
    
    Object = read champ.get (object); 
    
    } Catch (IllegalArgumentException e) 
    
    { 
    
    // The parameter passed is invalid (not the right type for example) 
    
    e.printStackTrace (); 
    
    } Catch (IllegalAccessException e) 
    
    { 
    
    // Function not available 
    
    e.printStackTrace (); 
    
    }

  5. #5
    Join Date
    Jul 2010
    Posts
    118

    Re: How to use Reflection in Java

    To conclude, as you can see, the reflection is very simple and opens up many possibilities. However, just because you've learned a new concept, it is not a reason to use it all the sauces! Sometimes it is much easier to use interfaces or abstract classes. A disadvantage of the thinking is the lack of readability of the code. Reflection is useful for performing automatic processing on the content objects. Personally, in a project website, to display all information of an object in a page automatically (that is to say stuff without one to one access to all fields of the object), the use of reflection has been practical and has saved me a lot of time. Indeed, in every page, while browsing the contents of an object by reflection, in a few lines, I assure that at the least structural change of the object (eg adding a field in this one) that the repercussions are made automatically without any effort on all pages displaying that object. With that, I hope you enjoy Java..

Similar Threads

  1. Generics vs. Reflection in Java
    By Jagruti23 in forum Software Development
    Replies: 9
    Last Post: 15-09-2010, 09:36 PM
  2. Remoting and Reflection in C#
    By BansiJ in forum Software Development
    Replies: 5
    Last Post: 04-12-2009, 07:13 PM
  3. C # generic classes reflection
    By Wyvern in forum Software Development
    Replies: 3
    Last Post: 26-10-2009, 05:11 PM
  4. Download Wrq Reflection Suite
    By TAARIQ in forum Operating Systems
    Replies: 3
    Last Post: 04-06-2009, 09:54 PM
  5. Java Programming Language Basics: Reflection Basics and Class Class
    By mayuri_gunjan in forum Guides & Tutorials
    Replies: 6
    Last Post: 29-08-2005, 12:04 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,714,042,471.51279 seconds with 17 queries