- How to invoke method using reflection in java
- Invoke method without parameters
- Invoke method with parameters
- Invoke static method using reflection
- Invoke private method using reflection
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Get and set Fields using reflection in java
- Access private fields and methods using reflection in java
- Invoke constructor using Reflection in java
- Invoke Getters And Setters Using Reflection in java
- Java Reflection tutorial
- How to Invoke Method by Name in Java Dynamically Using Reflection? Example
- Java Program to invoke method by name dynamically using Reflection
- Important points while calling Java method using reflection:
How to invoke method using reflection in java
Let’s understand this with the help of the example.
Create a class named Employee.java . We will invoke this class’s method using reflection.
Create a main method named EmployeeReflectionMain.java .
| NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e )
When you run above program, you will get below output:
Explanation
You need to first create an object of Class.We will get all the info such as constructors, methods and fields using this cls object.
Invoke method without parameters
You need to use getDeclareMethod() to get toString() method and toString() do not have any parameter hence, we will pass empty params.
Invoke method with parameters
As printName() is public method, we can use getMethod() to get method of the object and pass String parameter to printName() method.
Invoke static method using reflection
As you can see, we don’t require any object for static method, we are invoking methods using method.invoke(null,null).
Invoke private method using reflection
If you want to invoke private method using reflection, you need call method.setAccessible(true) explicitly and then only you can access private method.
Was this post helpful?
Share this
Related Posts
Author
Related Posts
Get and set Fields using reflection in java
Table of ContentsGet all fields of the classGet particular field of the classGetting and setting Field valueGetting and setting static Field value In this post, we will see how to get and set fields using reflection in java. java.lang.reflect.Field can be used to get/set fields(member variables) at runtime using reflection. Get all fields of the […]
Access private fields and methods using reflection in java
Table of ContentsAccess private fieldAccess private method In this post, we will see how to access private fields and methods using reflection in java. Can you access private fields and methods using reflection? Yes, you can. It is very easy as well. You just need to call .setAccessible(true) on field or method object which you […]
Invoke constructor using Reflection in java
Table of ContentsInstantiate Constructor with no parametersInstantiate Constructor with parametersConstructor parameters for primitive typesConclusion In this post, we will see how to invoke constructor using reflection in java. You can retrieve the constructors of the classes and instantiate object at run time using reflection. java.lang.reflect.Constructor is used to instantiate the objects. Instantiate Constructor with no […]
Invoke Getters And Setters Using Reflection in java
Table of ContentsUsing PropertyDescriptorUsing Class’s getDeclaredMethods In this post, we will see how to call getters and setters using reflection in java. We have already seen how to invoke method using reflection in java. There are two ways to invoke getter and setter using reflection in java. Using PropertyDescriptor You can use PropertyDescriptor to call […]
Java Reflection tutorial
Table of ContentsIntroductionThe ‘reflect’ packageFieldModifierProxyMethodConstructorArrayUses of Reflection in JavaExtensibilityDeveloping IDEs and Class BrowsersDebugging and Testing toolsDisadvantages of ReflectionLow PerformaceSecurity RiskExposure of Internal Fields and AttributesJava.lang.Class – the gateway to ReflectionImportant Methods of java.lang.ClassforName() method:getConstructors() and getDeclaredConstructors() methods:getMethods() and getDeclaredMethods()getFields() and getDeclaredFields() methods:Conclusion Introduction Reflection, as we know from the common term, is an image of […]
How to Invoke Method by Name in Java Dynamically Using Reflection? Example
In Java you can invoke any method by its string name dynamically using reflection API. java.lang.reflect API provides powerful reflection mechanism which can load classes by its name even if classes are not available at compile time, Can get all methods including private and public from class and allow you to invoke any method dynamically using reflection. For those who are new to Java this sound pretty strange that at runtime you provide a method name using string and Java can run that method without any code for calling the method during compilation, but Reflection is such a powerful mechanism it allows to do a lot of stuff dynamically and if you been using IDE like Netbeans or Eclipse, a J2EE framework like Spring and Struts , these all used reflection to provide powerful configuration module and several other useful features like code assist etc.
Reflection is very comprehensive topic and there is a lot to learn but we will start with simple Java program example to invoke a method using reflection in by providing name of method as String value.
This Java article is continuation of my post on covering basic concepts like static and dynamic binding in Java, when to use Interface in Java and why use PreparedStaement in Java. If you are new here or haven’t read them already then you may find them useful.
Java Program to invoke method by name dynamically using Reflection
java.lang.reflect package have a class called Method which represent method Reflectively and Method.invoke() is used to call any Java method dynamically using reflection. Method.invoke() takes an object whose method has to call and list of parameters to be passed to method and throws InvocationTargetException if called method throws any Exception. here is complete code example of calling method dynamically in Java using Reflection:
import java.lang.reflect.InvocationTargetException ;
import java.lang.reflect.Method ;
import java.util.List ;
/**
* Simple Java program to invoke method by providing name as String.
* Reflective calls are slower than normal call so calling method using reflection
* should be use carefully.
*/
public class MethodInvocationReflection
public static void main ( String args []) <
Class loadedList = null ;
List list = null ;
try <
//loading class dynamically using reflection
loadedList = Class. forName ( «java.util.ArrayList» ) ;
list = ( List ) loadedList. newInstance () ;
//calling method using an interface on a reflective instance
list. add ( «abc» ) ;
list. add ( «bcd» ) ;
> catch ( InstantiationException ex ) <
System. err . println ( «Not able to create Instance of Class» ) ;
> catch ( IllegalAccessException ex ) <
System. err . println ( «Not able to access Class» ) ;
> catch ( ClassNotFoundException ex ) <
System. err . println ( «Not able to find Class» ) ;
>
try <
//getting method instance reflectively
Method m = loadedList. getMethod ( «size» , ( Class []) null ) ;
//calling method in java using reflection dynamically
Object size = m. invoke ( list, ( Object []) null ) ;
System. out . println ( «Result of dynamically invoking method in Java, Size: » + size ) ;
> catch ( NoSuchMethodException ex ) <
System. err . println ( «Not able to find 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 by String in Java» ) ;
ex. printStackTrace () ;
>
>
>
Important points while calling Java method using reflection:
Here are few points worth noting while invoking method by giving its name and using reflection, I agree that reflection provides flexibility but it also has some disadvantage :
1) Reflection in Java has serious performance issues and calling same method reflectively is more than 2 to 3 times slower than normal method call even in modern JVM, So use reflection only if its genuinely needed and there is no other way around.
2) Invoking method using reflection also has some disadvantage like compile time checking of method parameters, order of parameters and return type etc. Since we use method.invoke() to call methods we lose all compile time checks and any typo or error will only be reflected in run time wrapped under InvocationTargetException .
3) Another problem is too much code for invoking method or creating instance using reflection as you see we have written 20 line of code to invoke a method which can be converted into just two lines if you call any method normally.
4) Last thing to note is using Interface object for calling method instead of using reflection or invoking method by name. if you see above Java program to invoked method by name, we have used List interface type to refer object created using reflection and called method List.add() like normal method only List.size() is called reflectively . This is one of best practices while using reflection.
That’s all on how to invoke method by name in Java dynamically using Reflection. Reflection is powerful but use it with caution. Call method with it’s interface even if Class is loaded dynamically using reflection, that is better than calling method by its string name using method.invoke() .