- 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
- Calling a method via reflection in Java: details
- Class lookup
- Method parameters
- Dealing with primitive parameters
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 […]
Calling a method via reflection in Java: details
On the previous page, we introduced the Java reflection API and showed a simple example of calling the String.length() method on a given string via reflection. On this page, we follow that example up with some further observations and common variations.
Class lookup
In this case, we looked up the class «manually» via Class.forName(). However, if the class name is fixed and resolvable at compile time, as it might well be in various typical cases, the compiler actually allows us to write the following shorthand:
Method lenMethod = String.class.getDeclaredMethod(. );
Method parameters
A method is defined not only by its name, but also by the list of parameters it can take. As you’re probably aware, Java permits polymorphism: that is, various methods can exist on the same class provided that they have different parameter lists. Therefore, when we retrieve a Method object, we must supply not just the name, but also a list of parameter types. The list of paramter types is supplied as an array of Class objects, although in the case of a method like String.length() that takes no parameters, the array is empty.
When we do have to supply a Class object representing a parameter type, using the above compiler shortcut for looking up the Class object can be useful. For example, we could retrieve String.endsWith() method (which takes a single String parameter) as follows:
String.class.getDeclaredMethod("endsWith", new Class[] < String.class >);
In the invoke() call, we would then supply the string in question inside the object array (which was empty in the above example):
boolean b = (Boolean) lenMethod.invoke(stringObj, new Object[] <>);
Dealing with primitive parameters
Using reflection to call methods that take primitive parameters can be slightly confusing at first. Let’s take the example of calling the two-parameter version of String.substring() via reflection. We might have expected to perform the method lookup as follows:
// This is actually WRONG! String.class.getDeclaredMethod("substring", new Class[] < Integer.class, Integer.class >);
Well, if you try this, you’ll find that a NoSuchMethodException is thrown. Why? Well, because the above code is looking for a method that takes two Integer objects as its parameters, not to int primitives!
How do we fix this? Well, it turns out that the solution is the little-used .TYPE field that exists on the various wrapper classes (Integer.TYPE, Long.TYPE etc). These fields contain a reference to a special Class object that represents the primitive type. So the correct version of the above line would be:
String.class.getDeclaredMethod("substring", new Class[] < Integer.TYPE, Integer.TYPE >);
On the other hand, when we invoke the method via Method.invoke(), we pass in a wrapper object for the primitive values:
substringMethod.invoke(stringObj, new Object[] < new Integer(0), new Integer(4) >);
However in practice, as of Java 5, the compiler allows us to write the following:
substringMethod.invoke(stringObj, new Object[] );
However, note that this is essentially a compiler trick; what actually gets placed into the array are obviously corresponding Integer objects.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants. Follow @BitterCoffey
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.