How To Invoke Method Past Times Advert Inwards Coffee Dynamically Using Reflection

In Java yous tin flaming invoke whatsoever method past times its string advert dynamically using reflection API. java.lang.reflect API provides powerful reflection machinery which tin flaming charge classes past times its advert fifty-fifty if classes are non available at compile time, Can acquire all methods including private as well as populace from class as well as allow yous to invoke whatsoever method dynamically using reflection. For those who are novel inwards Java this audio pretty foreign that at runtime yous furnish a method advert using string as well as Java tin flaming run that method without whatsoever code for calling the method during compilation, but Reflection is such a powerful machinery it allows to do lot of materials dynamically as well as if yous been using IDE similar Netbeans or Eclipse , J2EE framework similar Spring as well as Struts, these all used reflection to furnish powerful configuration module as well as several other useful characteristic similar code assist etc. Reflection is really comprehensive theme as well as in that place is a lot to larn but nosotros volition offset alongside elementary Java plan illustration to invoke a method using reflection inwards  by providing advert of method equally String value.  

This Java article is continuation of my post service on roofing basic concepts similar static as well as dynamic binding inwards Javawhen to purpose Interface inwards Java as well as why purpose PreparedStaement inwards Java. If yous are novel hither or haven’t read them already as well as hence yous may uncovering them useful.


Java Program to invoke method past times advert dynamically using Reflection

invoke whatsoever method past times its string advert dynamically using reflection API How to Invoke Method past times Name inwards Java Dynamically Using ReflectionException. hither is consummate code illustration of calling method dynamically inwards Java using Reflection:


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Simple Java plan to invoke method past times providing advert equally String.
 * Reflective calls are slower than normal telephone phone hence calling method using reflection
 * should endure purpose carefully.
 */

public class MethodInvocationReflection {

    public static void main(String args[]) {
       Class loadedList = null;
       List listing = null;
       try {
            //loading degree dynamically using reflection
            loadedList = Class.forName("java.util.ArrayList");
            listing = (List) loadedList.newInstance();
         
            //calling method using interface on reflective instance
            list.add("abc");
            list.add("bcd");

        } catch (InstantiationException ex) {
            System.err.println("Not able to do Instance of Class");
        } catch (IllegalAccessException ex) {
            System.err.println("Not able to access Class");
        } catch (ClassNotFoundException ex) {
            System.err.println("Not able to uncovering Class");
        }
   
       try {
            //getting method event reflectively
            Method one thousand = loadedList.getMethod("size", (Class[]) null);
         
            //calling method inwards coffee using reflection dynamically
            Object size = m.invoke(list, (Object[]) null);
            System.out.println("Result of dynamically invoking method inwards Java, Size: " + size);

        } catch (NoSuchMethodException ex) {
            System.err.println("Not able to uncovering Method on class");
            ex.printStackTrace();
        } catch (SecurityException ex) {
            System.err.println("Security Exception raised");
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            System.err.println("Not able to access method ");
            ex.printStackTrace();
        } catch (IllegalArgumentException ex) {
            System.err.println("Incorrect supplied arguments");
            ex.printStackTrace();
        } catch (InvocationTargetException ex) {
            System.err.println("Not able to invoke method past times String inwards Java");
            ex.printStackTrace();
        }
    }
}

Important points land calling Java method using reflection:

Here are few points worth noting land invoking method past times giving its advert as well as using reflection, I concur that reflection provides flexibility but it also has to a greater extent than or less disadvantage :

1) Reflection inwards Java has serious functioning issues as well as calling same method reflectively is to a greater extent than than 2 to iii times slower than normal method telephone phone fifty-fifty inwards modern JVM, So purpose reflection alone if its truly needed as well as in that place is no other means around.

2) Invoking method using reflection also has to a greater extent than or less disadvantage similar compile fourth dimension checking of method parameters, order of parameters as well as return type etc. Since nosotros purpose method.invoke() to telephone phone methods we lose all compile fourth dimension checks as well as whatsoever typo or mistake volition alone endure reflected inwards run fourth dimension wrapped nether InvocationTargetException.

3) Another work is too much code for invoking method or creating event using reflection equally yous meet nosotros bring written twenty draw of piece of work of code to invoke method which tin flaming endure converted into but ii lines if yous telephone phone whatsoever method normally.

4) Last matter to Federal Reserve annotation is using Interface object for calling method instead of using reflection or invoking method past times name. if yous meet inwards a higher house Java plan to invoked method past times name,  we bring used List interface type to refer object created using reflection as well as called method List.add() similar normal method only List.size() is called reflectively. This is ane of best practices land using reflection.

That's all on how to invoke method past times advert inwards Java dynamically using Reflection. Reflection is powerful but purpose it alongside caution. Call method alongside it’s interface fifty-fifty if Class is loaded dynamically using reflection, that is amend than calling method past times its string advert using method.invoke().

Further Learning
Complete Java Masterclass
6 JDBC functioning tips for Java application

Komentar

Postingan populer dari blog ini

Difference Betwixt Struts Validatorform Vs Validatoractionform - Interview Question

How To Convert Inputstream To Byte Array Inwards Coffee - Two Examples

Difference Betwixt Fileinputstream Together With Filereader Inwards Coffee | Inputstream Vs Reader