|
|
![]() |
| Thread Tools | Search this Thread |
#1
| |||
| |||
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:
|
#2
| |||
| |||
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 { } }
Code: Class class = obj.getClass (); Code: Class class = String.class;
|
#3
| |||
| |||
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 (); Code: Class class = String.class; 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 (); Code: Concat = class.getMethod ("concat", String.class); 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 foundThus, 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 (); } 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 (); 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 (); } 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 (); 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 (); } |
#4
| |||
| |||
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 (); } IllegalArgumentException: the number of arguments is not good or are the wrong size2. 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 (); } IllegalArgumentException: the number of arguments is not good or are the wrong size3. 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 (); } IllegalArgumentException: value field to be defined is not the right type4. 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
| |||
| |||
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.. ![]() |
![]() |
|
Tags: c program, code, exception handling, java, reflection, string |
Thread Tools | Search this Thread |
|
![]() | ||||
Thread | Thread Starter | Forum | Replies | Last Post |
Generics vs. Reflection in Java | Jagruti23 | Software Development | 9 | 15-09-2010 09:36 PM |
Remoting and Reflection in C# | BansiJ | Software Development | 5 | 04-12-2009 07:13 PM |
C # generic classes reflection | Wyvern | Software Development | 3 | 26-10-2009 05:11 PM |
Download Wrq Reflection Suite | TAARIQ | Operating Systems | 3 | 04-06-2009 09:54 PM |
Java Programming Language Basics: Reflection Basics and Class Class | mayuri_gunjan | Guides & Tutorials | 6 | 29-08-2005 12:04 AM |