Skip to main content

How to Use Reflection to Call Methods in Java?

--
You can invoke methods on objects dynamically. First, you must get their definition through one of the methods Class.getMethod(String,Class[]) or Class.getDeclaredMethod(String,Class[]). The first parameter is the method??s name and the second is an array of Class objects representing the types of its parameters.
The getMethod can handle inheritance but only picks up public methods. It returns the public method that matches the parameters provided, whether it is declared by the class or inherited.
class Parent { 
    public long l;
    public void setLong(long l) {
        this.l = l;
    } 
}

public class Program extends Parent {
 
    public static void main(String[] args) {
     
        // Get the Class object associated with this class. 
        Program program = new Program();
        Class progClass = program.getClass();
        
        try { 
          // Get the method named sayHello.
          Method helloMethod = progClass.getMethod( "sayHello", null);
          System.out.println("Method found: " + helloMethod.toString());
        } 
        catch (NoSuchMethodException ex) {
            System.out.println(ex.toString());
        }
        
        try {
          // Get the method named setStr.
          Class[] args1 = {String.class};
          Method strMethod = progClass.getMethod( "setStr", args1); 
          System.out.println("Method found: " + strMethod.toString());
        } 
        catch (NoSuchMethodException ex) {
            System.out.println(ex.toString());
        }

try { 
          // Get the method named setDate. 
          Class[] args2 ={Date.class};
          Method dateMethod = progClass.getMethod( "setDate", args2);
          System.out.println("Method found: " + dateMethod.toString());

        } 
        catch (NoSuchMethodException ex) {
            System.out.println(ex.toString());
        }

        try { 
          // Get the method named setI.
          Class[] args3 = {Integer.TYPE};
          Method iMethod = progClass.getMethod( "setI", args3);
          System.out.println("Method found: " + iMethod.toString());
        } 
        catch (NoSuchMethodException ex) {
            System.out.println(ex.toString());
        }

        try { 
            // Get the method named setI. 
            Class[] args4 ={Long.TYPE};
            Method lMethod = progClass.getMethod( "setLong", args4); 
            System.out.println("Method found: " + lMethod.toString());
        } 
        catch (NoSuchMethodException ex) {
            System.out.println(ex.toString());
        }
    }

    public String sayHello()
    {
        return "Hello!";
    }

    public void setStr(String str)
    {
        this.str = str;
    }

    private void setDate(Date date)
    {
        this.date = date;
    }

    private void setI(int i)
    {
        this.i = i;
    }

    public String str = "Hello";
    private Date date = new Date();
    protected int i = 0;
}

/* Output
Method found: public java.lang.String com.abcd.Program.sayHello()
Method found: public void com.abcd.Program.setStr(java.lang.String)
java.lang.NoSuchMethodException: com.abcd.Program.setDate(java.util.Date)
java.lang.NoSuchMethodException: com.abcd.Program.setI(int)
Method found: public void com.abcd.Parent.setLong(long)
*/
The getDeclaredMethod returns all methods including package, protected, and private but exculding inherited methods.
class Parent { 
    public long l;
    public void setLong(long l) {
        this.l = l;
    } 
}

public class Program extends Parent {
 
    public static void main(String[] args) {
      try { 

         // Get the Class object associated with this class. 
         Program program = new Program();
         Class progClass = program.getClass(); 

         // Get the method named sayHello.
         Method helloMethod = progClass.getDeclaredMethod( "sayHello", null);
         System.out.println("Method found: " + helloMethod.toString());

         // Get the method named setStr.
         Class[] args1 = {String.class};
         Method strMethod = progClass.getDeclaredMethod( "setStr", args1); 
         System.out.println("Method found: " + strMethod.toString());

         // Get the method named setDate. 
         Class[] args2 ={Date.class};
         Method dateMethod = progClass.getDeclaredMethod( "setDate", args2);
         System.out.println("Method found: " + dateMethod.toString());

         // Get the method named setI.
         Class[] args3 = {Integer.TYPE};
         Method iMethod = progClass.getDeclaredMethod( "setI", args3);
         System.out.println("Method found: " + iMethod.toString());

         // Get the method named setI. 
         Class[] args4 ={Long.TYPE};
         Method lMethod = progClass.getDeclaredMethod( "setLong", args4); 
         System.out.println("Method found: " + lMethod.toString());
        } 
        catch (NoSuchMethodException ex) {
            System.out.println(ex.toString());
        }
    }

    public String sayHello()
    {
        return "Hello!";
    }

    public void setStr(String str)
    {
        this.str = str;
    }

    private void setDate(Date date)
    {
        this.date = date;
    }

    private void setI(int i)
    {
        this.i = i;
    }

    public String str = "Hello";
    private Date date = new Date();
    protected int i = 0;
}

/* Output
Method found: public java.lang.String com.abcd.Program.sayHello()
Method found: public void com.abcd.Program.setStr(java.lang.String)
Method found: private void com.abcd.Program.setDate(java.util.Date)
Method found: private void com.abcd.Program.setI(int)
java.lang.NoSuchMethodException: com.abcd.Program.setLong(long)
*/

Reflection is used to invoke a method when name of the method is supplied at run time. The method??s definition is represented by an instance of the java.lang.reflect.Method class. Using its API you can get any information you want about the method it represents. You can also invoke the method on an object using Method.invoke(Object,Object[]). The first argument is the object whose method you want to call (ignored if the method is static). The second is an array of objects corresponding to the parameters to be passed to the method that is invoked. If the parameter is a primitive type, the corresponding value in the argument array must be the appropriate wrapper object
package com.abcd;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

class Sample {
    static private int privateInt = 1;
    protected float protectedField = 1.2F;
    int[] data = { 4, 3, 2, 1 };
    public String message = "Hi world!";
    
    public Sample() {
        System.out.println( "Default Constructor" );
    }
    
    public Sample( String newMessage ) {
        System.out.println( "One arg Constructor"  );
        message = newMessage;
    }
    
    public final void setData( int[] newData ) {
        System.out.println( "Set data" );
        data = newData;
    }
    
    public void setFields( int anInt, float aFloat, 
                           String aMessage ) {
        System.out.println( "Set fields" );
        privateInt = anInt;
        protectedField = aFloat;
        message = aMessage;
    }
    
    public String toString() {
        StringBuffer str = new StringBuffer();
        str.append("[");
        for (int i: data) {
            str.append(i).append(" ");
        }
        str.append("]");  
        return "Sample(" + privateInt + ", " + 
                protectedField + ", " + 
                message + ", " + str.toString() +")";
    }
 }

public class Program 
{
    public static void main(String[] args) 
            throws SecurityException, 
                   NoSuchMethodException, 
                   InstantiationException, 
                   IllegalAccessException, 
                   IllegalArgumentException, 
                   InvocationTargetException
    {
        Class clz = Sample.class;
        Class[] argumentTypes = { int.class, float.class, String.class };
        Method setFields = clz.getMethod( "setFields", argumentTypes); 

        Class[] argumentTypes1 = { int[].class };
        Method setData = clz.getMethod( "setData", argumentTypes1);

        Object aSample =  clz.newInstance();
        System.out.println( aSample );
        
        Object[] arguments = { new Integer(23), new Float(100.35f), "Bye" };
        setFields.invoke( aSample, arguments );
        System.out.println( aSample );
 
        

        Constructor oneArgument = clz.getConstructor(java.lang.String.class); 
        Object newObject = oneArgument.newInstance( 
                 new Object[]{"Hi abcd!" } );
        System.out.println( newObject );
        int[] someData = { 1, 2, 3, 4 };
        Object[] arguments1 = { someData };
        setData.invoke( newObject, arguments1 );
        System.out.println( newObject );

    }
}

/* output
Default Constructor
Sample(1, 1.2, Hi world!, [4 3 2 1 ])
Set fields
Sample(23, 100.35, Bye, [4 3 2 1 ])
One arg Constructor
Sample(23, 1.2, Hi abcd!, [4 3 2 1 ])
Set data
Sample(23, 1.2, Hi abcd!, [1 2 3 4 ])
*/

Comments

Popular posts from this blog

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

XML Binding with JAXB 2.0 - Tutorial

Java Architecture for XML Binding (JAXB) is an API/framework that binds XML schema to Java representations. Java objects may then subsequently be used to marshal or unmarshal XML documents. Marshalling an XML document means creating an XML document from Java objects. Unmarshalling means creating creating a Java representation of an XML document (or, in effect, the reverse of marshaling). You retrieve the element and attribute values of the XML document from the Java representation. The JAXB 2.0 specification is implemented in JWSDP 2.0. JAXB 2.0 has some new features, which facilitate the marshalling and unmarshalling of an XML document. JAXB 2.0 also allows you to map a Java object to an XML document or an XML Schema. Some of the new features in JAXB 2.0 include: Smaller runtime libraries are required for JAXB 2.0, which require lesser runtime memory. Significantly, fewer Java classes are generated from a schema, compared to JAXB 1.0. For each top-level complexType, 2.0 generates a v