Reflection API Tutorials and Examples

download Reflection API Tutorials and Examples

of 22

Transcript of Reflection API Tutorials and Examples

  • 7/31/2019 Reflection API Tutorials and Examples

    1/22

    Reflection API Tutorials and Examples

    1. Reflection API : A Brief IntroductionIn this section you will learn about Reflection API and all of its methods.

    Reflection API is a powerful technique (that provides the facility) to find-out its

    environment as well as to inspect the class itself. Reflection API was included inJava 1.1.

    Here we are providing few of the examples to give a better overview of the

    Reflection API :

    2. Getting the implemented InterfacesIn this section you will learn how to retrieve an Interface (that included in theprogram) by using the getInterfaces() method. Here is an example that provides the

    usage of the getInterfaces() method in more detail.3. Retrieving t he class name through Reflection API

    A more generic way, how to retrieve the name of the class (that is used in theprogram) that reflects the package name by using the getName() method. Here is an

    example that provides the proper way to use the getName() method.

    4. Finding out the superclass name of the ClassHere we show you the way to find out the Superclass name by using the

    getSuperclass() method. The given example demonstrates the use of getSuperclass()

    method in more detail.5. Getting the method name used in the Application

    In this section we describe how to retrieve method name by using the getMethods()

    method. Here is an example that demonstrates the use of the getMethods() methodin more detail.6. Finding out the object of the Class

    This section illustrates how to retrieve an object name that reflects the package

    name by using the object.getClass() method. Here is an example that provides theproper usage of the object.getClass() method in more detail.

    7. Finding out the class fieldsThis section explores you, how to retrieve the fields of the class by using thegetFields() method. For this we are taking an example that provides the use of the

    getFields() method in detailed way.

    8. Getting information about Constructor

    In this section you will learn, how to retrieve the information about the constructorby using the getConstructors() method. Here is an example that provides the usage

    of the getConstructors() method.

    9. No Argument Constructor ExampleIn this section you will learn how to know that whether any class consists No-

    Argument Constructor or not ?. Here is an example that provides the usage of the

    newInstance() method in more detail.

    http://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/Interfaces.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtmlhttp://www.roseindia.net/java/reflect/Constructor.shtmlhttp://www.roseindia.net/java/reflect/no-argument-constructor.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/Interfaces.shtmlhttp://www.roseindia.net/java/reflect/Interfaces.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtmlhttp://www.roseindia.net/java/reflect/Constructor.shtmlhttp://www.roseindia.net/java/reflect/Constructor.shtmlhttp://www.roseindia.net/java/reflect/no-argument-constructor.shtml
  • 7/31/2019 Reflection API Tutorials and Examples

    2/22

  • 7/31/2019 Reflection API Tutorials and Examples

    3/22

    being used. It also provides an easy way to create aJava Application that was not possible

    before Java1.1. You can create methods like event handlers, hash code etc and also find-out the objects and classes.

    With the help of Reflection API you can get the information about any class of the

    java.lang package. There are some useful methods like getName() and getInterfaces(),which allows us to retrieve the name of the class and the interfaces of the packagerespectively.

    Avoid using Reflection API in thoseapplications wherever it affects the application's

    performance, security related code of the application such as in Applet programming.Reflection API also affects the application if the private fields and methods are there.

    Here we are providing few of the examples to give a better overview of the Reflection

    API :

    1. Getting the implemented InterfacesIn this section you will learn how to retrieve an Interface (that included in the program) byusing the getInterfaces() method. Here is an example that provides the usage of the

    getInterfaces() method in more detail.

    2. Retrieving t he class name through Reflection API

    A more generic way, how to retrieve the name of the class (that is used in the program) thatreflects the package name by using the getName() method. Here is an example that

    provides the proper way to use the getName() method.

    3. Finding out the superclass name of the Class

    Here we show you the way to find out the Superclass name by using the getSuperclass()method. The given example demonstrates the use of getSuperclass() method in more detail.

    4. Getting the method name used in the Application

    In this section we describe how to retrieve method name by using the getMethods()method. Here is an example that demonstrates the use of the getMethods() method in more

    detail.

    5. Finding out the object of the Class

    This section illustrates how to retrieve an object name that reflects the package name byusing the object.getClass() method. Here is an example that provides the proper usage of

    the object.getClass() method in more detail.

    6. Finding out the class fields

    This section explores you, how to retrieve the fields of the class by using the getFields()method. For this we are taking an example that provides the use of the getFields() method

    in detailed way.

    http://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/Interfaces.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/Interfaces.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtml
  • 7/31/2019 Reflection API Tutorials and Examples

    4/22

    7. Getting information about Constructor

    In this section you will learn, how to retrieve the information about the constructor by

    using the getConstructors() method. Here is an example that provides the usage of thegetConstructors() method.

    Getting the implemented Interfaces

    In this section you will learn how to retrieve an Interface (that included in the program) by

    using the getInterfaces() method. Here is an example that provides the usage of the

    getInterfaces() method in more detail.

    Create an object of class Finterface and assign it with java.util.Integer.class.. Now retrieveInterfaces (included in the program) and store their references in an array of class Class by

    using the getInterfaces() method.

    Here is the code of the Example :

    Finterface.java:

    import java.lang.reflect.*;

    public class Finterface {public static voidmain(String str[]){

    Class cls = java.util.List.class; Class[] intfs = cls.getInterfaces(); int len = intfs.length; for (int i =0; i < len; i++) { System.out.println(intfs[i]); }

    }}

    Here is the output of this Example :

    C:\roseindia>javac

    Finterface.java

    C:\roseindia>java

    Finterface

    interface

    java.util.Collection

    http://www.roseindia.net/java/reflect/Constructor.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/reflectionOverview.shtmlhttp://www.roseindia.net/java/reflect/Constructor.shtml
  • 7/31/2019 Reflection API Tutorials and Examples

    5/22

    Download this Example:

    Retrieving the class name throughReflection API

    A more generic way, how to retrieve the name of the class (that is used in the program) that

    reflects the package name by using the getName() method. Here is an example that

    provides the proper way to use the getName() method.

    Here we create an object of class Fclass and assign the reference of the classjava.util.Integer.class to it. Now retrieve the class name (that is included in the program) by

    using the getName() method.

    Here is the code of the Example :

    Fclass.java

    import java.lang.reflect.*;public class Fclass{public static voidmain(String[] args){ Class cls = java.lang.Integer.class; String info; info = cls.getName(); // It will show java.lang.Integer System.out.println(info); }}

    Here is the output of the Example :

    C:\roseindia>javac

    Fclass.java

    C:\roseindia>java

    Fclass

    http://www.roseindia.net/java/reflect/Finterface.javahttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Interfaces.shtmlhttp://www.roseindia.net/java/reflect/Finterface.java
  • 7/31/2019 Reflection API Tutorials and Examples

    6/22

    java.lang.Integer

    Download this Example:

    Finding out the super class name of the

    class

    Here we show you the way to find out the Superclass name by using the getSuperclass()

    method. The given example demonstrates the use of getSuperclass() method in more detail.

    Create a class "Fsupercls". Populate it with the Checkbox objects. Now retrieve the

    Superclass name by using the getSuperclass() method.

    Here is the code of the Example :

    Fsupercls.java:

    import java.lang.reflect.*;import java.awt.*;

    public class Fsupercls {

    public static voidmain(String[] args) { Checkbox big = new Checkbox(); printName(big); } static voidprintName(Object objct) { Class cls = objct.getClass(); Class sup = cls.getSuperclass();

    System.out.println(sup); }}

    Here is the output of the Example :

    C:\roseindia>javac

    Fsupercls.java

    C:\roseindia>java

    Fsupercls

    class

    java.awt.Component

    http://www.roseindia.net/java/reflect/Fclass.javahttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Class.shtmlhttp://www.roseindia.net/java/reflect/Fclass.java
  • 7/31/2019 Reflection API Tutorials and Examples

    7/22

    Download this Example:

    Getting the method name used in theApplication

    In this section we describe how to retrieve method name by using the getMethods()method. Here is an example that demonstrates the use of the getMethods() method in more

    detail.

    Define a class named "Fmethod" and then create an object of this class and get the

    reference of java.util.Integer.class into it. Now retrieve the method name by using thegetMethods() method.

    Here is the code of the Example :

    Fmethod.java:

    import java.lang.reflect.*;

    public class Fmethod{public static voidmain(String[] args){ Class cls = java.lang.Integer.class;

    Method method = cls.getMethods()[0]; String info; info = method.getName();

    System.out.println(info); }}

    Here is the output of the Example :

    C:\roseindia>javac

    Fmethod.java

    C:\roseindia>javaFmethod

    hashCode

    Download this Example:

    http://www.roseindia.net/java/reflect/Fsupercls.javahttp://www.roseindia.net/java/reflect/Fmethod.javahttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Superclass.shtmlhttp://www.roseindia.net/java/reflect/Fsupercls.javahttp://www.roseindia.net/java/reflect/Fmethod.java
  • 7/31/2019 Reflection API Tutorials and Examples

    8/22

    Finding out the object of the class

    This section illustrates how to retrieve an object name that reflects the package name byusing the object.getClass() method. Here is an example that provides the proper usage of

    the object.getClass() method in more detail.

    Create a class "Fobject" with an object Checkbox. Now retrieve an object name that

    reflects the package name by using the object.getClass() method.

    Here is the code of the Example :

    Fobject.java:

    import java.lang.reflect.*;import java.awt.*;

    public lass Fobject{ public static voidmain(String[] args) { Checkbox bos = new Checkbox(); printName(bos); } static voidprintName(Object objct) { Class cls = objct.getClass(); String strng = cls.getName(); System.out.println(strng); }}

    Here is the output of the Example :

    C:\roseindia>javac

    Fobject.java

    C:\roseindia>java

    Fobject

    java.awt.Checkbox

    Download this Example:

    Finding out the class fields

    http://www.roseindia.net/java/reflect/Fobject.javahttp://www.roseindia.net/java/reflect/Constructor.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Object.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Method.shtmlhttp://www.roseindia.net/java/reflect/Fobject.java
  • 7/31/2019 Reflection API Tutorials and Examples

    9/22

    This section explores you, how to retrieve the fields of the class by using the getFields()

    method. For this we are taking an example that provides the use of the getFields() method

    in detailed way.

    Create a class "Ffield" and create an object of this class and assign it the reference of

    java.util.Integer.class class. Now retrieve the class fields by using the getFields() method.

    Here is the code of the Example :

    Ffield.java:

    import java.lang.reflect.*;

    public class Ffield{public static voidmain(String[] args){ Class cls = java.lang.String.class; Field field = cls.getFields()[0];

    String name; name = field.getName(); // It'll show CASE_INSENSITIVE_ORDER System.out.println(name); }}

    Here is the output of the Example :

    C:\roseindia>javac Ffield.java

    C:\roseindia>java Ffield

    CASE_INSENSITIVE_ORDER

    Download this Example:

    Getting information about Constructor

    In this section you will learn, how to retrieve the information about the constructor by

    using the getConstructors() method. Here is an example that provides the usage of thegetConstructors() method.

    Declare a class "Fconstructor" and then create an object of this class and take the referenceof the class java.util.Integer.class into it. Make a Constructor named constructor. Now

    retrieve the name of the constructor by using the getConstructors() method.

    Here is the code of the Example :

    http://www.roseindia.net/java/reflect/Ffield.javahttp://www.roseindia.net/java/reflect/no-argument-constructor.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Fields.shtmlhttp://www.roseindia.net/java/reflect/Ffield.java
  • 7/31/2019 Reflection API Tutorials and Examples

    10/22

    Fconstructor.java

    import java.lang.reflect.*;

    public class Fconstructor{public static voidmain(String[] args){ Class cls = java.lang.String.class; Constructor constructor = cls.getConstructors()[0]; String name; name = constructor.getName(); //It'll show java.lang.String System.out.println(name); }

    }

    Here is the output of the Example :

    C:\roseindia>javac

    Fconstructor.java

    C:\roseindia>java Fconstructor

    java.lang.String

    Download this Example:

    No Argument Constructor Example

    In this section you will learn how to know that whether any class consists No-Argument

    Constructor or not ?. Here is an example that provides the usage of the newInstance()method in more detail.

    Here in our example we have used "forName()" static method ofClass and then we have

    invoked newInstance() method to create a new object without any argument.Invoking

    newInstance() method throws a NoSuchMethodException if the class does not have anyno-argument constructor.

    Here is code for example:

    http://www.roseindia.net/java/reflect/Fconstructor.javahttp://www.roseindia.net/java/reflect/method-information-example.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/Constructor.shtmlhttp://www.roseindia.net/java/reflect/Fconstructor.java
  • 7/31/2019 Reflection API Tutorials and Examples

    11/22

    NoArgConstructor.java

    import java.lang.reflect.*;import java.util.ArrayList;

    public class NoArgConstructor {public static voidmain(String str[]){ try{ ArrayList list = (ArrayList)

    (Class.forName("java.util.ArrayList").newInstance()); System.out.println("No-Argument Constructor exist."); System.out.println("New Object created Successfully");

    }catch(Exception e){ System.out.println("No-argument constructor does not exist."); System.out.println(e.getMessage()); } }}

    Output:

    Download Source code

    Getting Methods Information of a class

    In this part of tutorialyou will learn how to retrieve information of all methods of a class

    (that included in the program) by using the getMethods() method. Here is an example thatprovides the usage of the getMethods() method in more detail.

    http://www.roseindia.net/java/reflect/NoArgConstructor.ziphttp://www.roseindia.net/java/reflect/identifying-array.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/no-argument-constructor.shtmlhttp://www.roseindia.net/java/reflect/NoArgConstructor.zip
  • 7/31/2019 Reflection API Tutorials and Examples

    12/22

    Create an object of class. Now retrieve all methods list in Method[] array. Now we can get

    other information of that methods by using different methods on that method object.

    Here is the example code ofMethodInfo.java

    MethodInfo.java

    import java.lang.reflect.*;import java.util.HashSet;

    public class MethodInfo{public static voidmain(String str[]){ HashSet set = new HashSet(); Class classObj = set.getClass(); Method[] methods = classObj.getMethods(); for (int i = 0; i < methods.length; i++) { String methodName = methods[i].getName(); System.out.println("Name: " + methodName); String returnString = methods[i].getReturnType().getName(); System.out.println("Return Type: " + returnString); Class[] parameterTypes =

    methods[i].getParameterTypes(); System.out.print("Parameter Types: "); for (int k = 0; k < parameterTypes.length; k ++) { String parameterName =

    parameterTypes[k].getName(); System.out.print(" " + parameterName); } System.out.println(); } }}

    Output:

  • 7/31/2019 Reflection API Tutorials and Examples

    13/22

    Download Source Code

    Identifying array using Reflection

    In this section we will describe you how to identify the object is Array or not ? with the useofboolean method isArray(). Here is an example that demonstrates the use of the

    isArray() method for identification ofArray object.

    In our example we are taking two variable objects of type integer and String respectively.

    In these two one is an array and another is not.So when we will call isArray() method onthem then Array variable "var" returns true hence you will get the following message on

    your command prompt. "var is an Array" and will return "false" in case of string object

    "notvar".

    Here is the example code forIdentifyArray class:

    http://www.roseindia.net/java/reflect/MethodInfo.ziphttp://www.roseindia.net/java/reflect/getting-fields.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/method-information-example.shtmlhttp://www.roseindia.net/java/reflect/MethodInfo.zip
  • 7/31/2019 Reflection API Tutorials and Examples

    14/22

    IdentifyArray.java

    import java.lang.reflect.*;

    public class IdentifyArray {public static voidmain(String str[]){ int[] var = {1,2,3,4}; String notvar="Hello"; Class varcls= var.getClass(); Class notvarcls= notvar.getClass(); if(varcls.isArray()) System.out.println(" var is an Array "); else System.out.println(" var is not an Array "); if(notvarcls.isArray()) System.out.println(" notvar is an Array "); else System.out.println(" notvar is not an Array "); }}

    Output:

    Getting Fields Information of a class

    In this section of"Reflection Tutorial" you will know how to retrieve the specific field

    of any class by using the getField() method. For this we are taking an example that

    http://www.roseindia.net/java/reflect/getting-component-type.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/identifying-array.shtml
  • 7/31/2019 Reflection API Tutorials and Examples

    15/22

    provides the use of the getField() method in detailed way.

    Create an object of "Rectangle" and then by invoking getClass() method we will have aclass object that will be able to call getField() .

    getField("x") returns x-axis field object getField("y") returns y-axis field object

    getField("height") returns height field object getField("width") returns width field object

    Since all these fields values are ofinteger type so we have to use getInt()

    method.

    Here is the full code forGettingField class :

    Getting Field.java

    import java.awt.*;import java.lang.reflect.*;

    public class GettingField{public static voidmain(String[] args) throws Exception{ Rectangle rect=new Rectangle(50,60); Field xfield = rect.getClass().getField("x"); Field yfield = rect.getClass().getField("y");

    Field heightField = rect.getClass().getField("height"); Field widthField = rect.getClass().getField("width"); System.out.println("X Value = "+ xfield.getInt(rect)); System.out.println("Y Value = "+ yfield.getInt(rect)); System.out.println("Height Value = "+ heightField.getInt(rect)); System.out.println("Width Value = "+ widthField.getInt(rect)); }}

    Output:

  • 7/31/2019 Reflection API Tutorials and Examples

    16/22

    Download this Example

    Getting Component type

    In this section you will come to know that how you can retrieve Component Type of an

    array's element. The component type of an Array is the type of array's element. For

    example if we have an integer type array then its component type will also be integer.

    Here is the example code ofComponentType class :

    ComponentType.java

    import java.lang.reflect.*;

    public class ComponentType {public static voidmain(String str[]){ int[] intvar = {1,2,3,4}; double[] doublevar = {1.0,2.2,3.5,4.8}; Class intcls= intvar.getClass(); Class doublecls= doublevar.getClass();System.out.println(" \"intvar\" component type => "

    +intcls.getComponentType());System.out.println(" \"doublevar\" cpmponent type => " +doublecls.getComponentType());

    }}

    To run this example create and save ComponentType.java and compile it. Aftercompilation execute ComponentType.class file.

    Output:

    http://www.roseindia.net/java/reflect/GettingField.ziphttp://www.roseindia.net/java/reflect/examine-interface.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/getting-fields.shtmlhttp://www.roseindia.net/java/reflect/GettingField.zip
  • 7/31/2019 Reflection API Tutorials and Examples

    17/22

    Examine Interface Example

    In this part of tutorial we will discuss how do you know that whether a given class is an

    "Interface" or a "Class"?

    To know that given class is an Interface or Class we can use boolean method isInterface()

    which returns true if given class is an Interface and false if it is a class.

    Here is the code for this example:

    import java.lang.reflect.*;

    public class ExamineInterface {public static voidmain(String str[]){ Class cls = java.util.List.class; Class[] intfs = cls.getInterfaces();

    int len = intfs.length; for (int i =0; i < len; i++){ System.out.println("Interface name is -->" +intfs[i].getName()); if (intfs[i].isInterface()) { System.out.println(intfs[i].getName()

    + " is an interface.");

    http://www.roseindia.net/java/reflect/class-modifier-example.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/getting-component-type.shtml
  • 7/31/2019 Reflection API Tutorials and Examples

    18/22

    } else { System.out.println(intfs[i].getName()

    + " is a class."); }

    } }}

    Output:

    Download Source Code

    Class Modifier Example

    In this section you will learn how to retrieve modifier's information of a class that we have

    taken in our program. Here is an example that provides the usage of the getModifiers()method in more detail.

    Create an object of class as you want and then call getModifiers() method through this

    object. We can also know is it "Public","Abstract","Final" with isPublic(),

    isAbstract(), isFinal() methods.

    Here is the code of example:

    ClassModifier.java

    import java.lang.reflect.*;

    http://www.roseindia.net/java/reflect/ExamineInterface.ziphttp://www.roseindia.net/java/reflect/calling-method.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/examine-interface.shtmlhttp://www.roseindia.net/java/reflect/ExamineInterface.zip
  • 7/31/2019 Reflection API Tutorials and Examples

    19/22

    public class ClassModifier {public static voidmain(String str[]){ Class cls = java.util.List.class; int modifier = cls.getModifiers(); if (Modifier.isPublic(modifier)) System.out.println("public"); if (Modifier.isAbstract(modifier)) System.out.println("abstract"); if (Modifier.isFinal(modifier)) System.out.println("final");

    }}

    Output:

    Download Source Code

    Calling ( Invoking ) Methods through

    Reflection

    In previous sections we have seen that how we can use "Reflection" to get information

    related to any Method. Now in this section of the tutorial you will come to know that we

    can also call methods of a class with the help of"Reflection".

    Since methods of a class either consists of arguments or do not have any argument. So incase of no-argument method noting to worry just simply get class of that object (as we have

    taken "String" in our example) and after getting class , get that particular method and toinvoke this method we have to use invoke() method.

    Here is the example code of CallingMethod :

    http://www.roseindia.net/java/reflect/ClassModifier.ziphttp://www.roseindia.net/java/reflect/setting-fields.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/class-modifier-example.shtmlhttp://www.roseindia.net/java/reflect/ClassModifier.zip
  • 7/31/2019 Reflection API Tutorials and Examples

    20/22

    CallingMethod.java

    import java.lang.reflect.*;

    public class CallingMethod { public static voidmain(String[] args) { String firstName= new String("Deepak"); String lastName=new String("Kumar"); String result = new String(""); Class cls = String.class; Class[] parametertype = new Class[] {String.class}; Object[] arguments = new Object[] {lastName}; try { Method concatMethod =

    cls.getMethod("concat", parametertype); result = (String)

    concatMethod.invoke(firstName,arguments); System.out.println(" Concatenated String is =>

    "+result); }catch (Exception e) { System.out.println(e); } }}

    Output:

    Download this Example Code

    Setting Fields Information of a class using

    Reflection

    As in our previous example we have seen that we can get field values of a class by using

    the Field class. Now we can also set different field values of that class by using set()

    method.

    http://www.roseindia.net/java/reflect/CallingMethod.ziphttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/index.shtmlhttp://www.roseindia.net/java/reflect/calling-method.shtmlhttp://www.roseindia.net/java/reflect/CallingMethod.zip
  • 7/31/2019 Reflection API Tutorials and Examples

    21/22

    In our class SettingField we have created an object of"Rectangle" and we can get fields

    of that object by using getField() method and we can retrieve values of that fields by get()

    method. Now we can set fields value by using set() methods.

    xfield.setInt(rect,new Integer(10)); yfield.setInt(rect,new Integer(10)); heightField.setInt(rect,new Integer(60));

    widthField.setInt(rect,new Integer(80));

    Above lines of code sets x-axis, y-axis, height, width field values. Since we are

    setting integer values to its field so I have used setInt() method.Here is the example code

    forSettingField class :

    SettingField.java

    import java.awt.*;import java.lang.reflect.*;

    public class SettingField{public static voidmain(String[] args) throws Exception{ Rectangle rect=new Rectangle(); Field xfield = rect.getClass().getField("x"); Field yfield = rect.getClass().getField("y"); Field heightField = rect.getClass().getField("height"); Field widthField = rect.getClass().getField("width"); System.out.println("---->> Before Setting Values > After Setting Values

  • 7/31/2019 Reflection API Tutorials and Examples

    22/22

    Output: