devxlogo

What Reflection Means in Java

What Reflection Means in Java

Through reflection, Java code can obtain information about, and performoperations on, data fields, methods, and constructors of loaded classes. Of coure, there are security restrictions.

The reflection API (encapsulated in “java.lang.reflect” package) represents classes, interfaces, and objects in the current Java Virtual Machine. Using the reflection API in tandem with “java.lang.Class” will render power to a wide range of computational initiatives, such as, GUI building, or debugger manufacturing.

Through reflection you can:
1. Determine the class of an object.
2. Get information about a class’s modifiers, fields, methods,constructors, and superclasses.
3. Find out what constants and method declarations belong to aninterface.
4. Create an instance of a class whose name is not known untilruntime.
5. Get and set the value of an object’s field, even if the field name is unknown to your program until runtime.
6. Invoke a method on an object, even if the method is not knownuntil runtime.
7. Create a new array, whose size and component type are not knownuntil runtime, and then modify the array’s components.

To work with the API, you need to obtain an instance of the Class class of an object, as in:

 	java.lang.Class c = Class.forName("java.util.GregorianCalendar");

Note that fully qualified names are essential. Then, you can obtain the class modifiers through a call like:

 	int modifier = c.getModifiers();

Then, you can test the modifiers using “public static boolean isPublic(int mod)”, “public static boolean isAbstract(int mod)”, and “public static boolean isFinal(int mod)” of java.lang.reflect.Modifier class. You can use a number of useful methods in java.lang.Class to know the super class of a class through “public native Class getSuperclass()”, the interfaces implemented by a class through “public native Class[] getInterfaces()”, constructors of the class through “public Constructor[] getConstructors()throws SecurityException”, the field names of a class through “publicField[] getFields() throws SecurityException”, the methods of a classthrough “public Method[] getMethods() throws SecurityException”.

Then youcan dynamically create an instance of the class through “public nativeObject newInstance() throws InstantiationException, IllegalAccessException”,as in:

                 Object obj = c.newInstance();

You can also use some methods of java.lang.reflect.Field to check the field values ofthe instance object you just created, as in:

 	try	{ 	    c = obj.getClass();                Field[] publicFields = c.getFields();                for (int i = 0; i 

devx-admin

Share the Post: