Java reflection private method invoke

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

Author

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 […]

Источник

Invoking Methods

Reflection provides a means for invoking methods on a class. Typically, this would only be necessary if it is not possible to cast an instance of the class to the desired type in non-reflective code. Methods are invoked with java.lang.reflect.Method.invoke() . The first argument is the object instance on which this particular method is to be invoked. (If the method is static , the first argument should be null .) Subsequent arguments are the method’s parameters. If the underlying method throws an exception, it will be wrapped by an java.lang.reflect.InvocationTargetException . The method’s original exception may be retrieved using the exception chaining mechanism’s InvocationTargetException.getCause() method.

Finding and Invoking a Method with a Specific Declaration

Consider a test suite which uses reflection to invoke private test methods in a given class. The Deet example searches for public methods in a class which begin with the string » test «, have a boolean return type, and a single Locale parameter. It then invokes each matching method.

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Locale; import static java.lang.System.out; import static java.lang.System.err; public class Deet  < private boolean testDeet(Locale l) < // getISO3Language() may throw a MissingResourceException out.format("Locale = %s, ISO Language Code = %s%n", l.getDisplayName(), l.getISO3Language()); return true; >private int testFoo(Locale l) < return 0; >private boolean testBar() < return true; >public static void main(String. args) < if (args.length != 4) < err.format("Usage: java Deet   %n"); return; > try < Classc = Class.forName(args[0]); Object t = c.newInstance(); Method[] allMethods = c.getDeclaredMethods(); for (Method m : allMethods) < String mname = m.getName(); if (!mname.startsWith("test") || (m.getGenericReturnType() != boolean.class)) < continue; >Type[] pType = m.getGenericParameterTypes(); if ((pType.length != 1) || Locale.class.isAssignableFrom(pType[0].getClass())) < continue; >out.format("invoking %s()%n", mname); try < m.setAccessible(true); Object o = m.invoke(t, new Locale(args[1], args[2], args[3])); out.format("%s() returned %b%n", mname, (Boolean) o); // Handle any exceptions thrown by method to be invoked. >catch (InvocationTargetException x) < Throwable cause = x.getCause(); err.format("invocation of %s failed: %s%n", mname, cause.getMessage()); >> // production code should handle these exceptions more gracefully > catch (ClassNotFoundException x) < x.printStackTrace(); >catch (InstantiationException x) < x.printStackTrace(); >catch (IllegalAccessException x) < x.printStackTrace(); >> >

Deet invokes getDeclaredMethods() which will return all methods explicitly declared in the class. Also, Class.isAssignableFrom() is used to determine whether the parameters of the located method are compatible with the desired invocation. Technically the code could have tested whether the following statement is true since Locale is final :

Locale.class == pType[0].getClass()
$ java Deet Deet ja JP JP invoking testDeet() Locale = Japanese (Japan,JP), ISO Language Code = jpn testDeet() returned true
$ java Deet Deet xx XX XX invoking testDeet() invocation of testDeet failed: Couldn't find 3-letter language code for xx

First, note that only testDeet() meets the declaration restrictions enforced by the code. Next, when testDeet() is passed an invalid argument it throws an unchecked java.util.MissingResourceException . In reflection, there is no distinction in the handling of checked versus unchecked exceptions. They are all wrapped in an InvocationTargetException

Invoking Methods with a Variable Number of Arguments

Method.invoke() may be used to pass a variable number of arguments to a method. The key concept to understand is that methods of variable arity are implemented as if the variable arguments are packed in an array.

The InvokeMain example illustrates how to invoke the main() entry point in any class and pass a set of arguments determined at runtime.

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; public class InvokeMain < public static void main(String. args) < try < Classc = Class.forName(args[0]); Class[] argTypes = new Class[] < String[].class >; Method main = c.getDeclaredMethod("main", argTypes); String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); System.out.format("invoking %s.main()%n", c.getName()); main.invoke(null, (Object)mainArgs); // production code should handle these exceptions more gracefully > catch (ClassNotFoundException x) < x.printStackTrace(); >catch (NoSuchMethodException x) < x.printStackTrace(); >catch (IllegalAccessException x) < x.printStackTrace(); >catch (InvocationTargetException x) < x.printStackTrace(); >> >

First, to find the main() method the code searches for a class with the name «main» with a single parameter that is an array of String Since main() is static , null is the first argument to Method.invoke() . The second argument is the array of arguments to be passed.

$ java InvokeMain Deet Deet ja JP JP invoking Deet.main() invoking testDeet() Locale = Japanese (Japan,JP), ISO Language Code = jpn testDeet() returned true

Источник

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Tuesday, February 9, 2021

Invoke Method at Runtime Using Java Reflection API

In this post we’ll see how to invoke a method at runtime using Java reflection API. You can even call a private method using reflection.

How to get the method instance

  • getMethod(String name, Class. parameterTypes)— Using getMethod() you can get a Method object for the specified public member method of the class (instance or static). As method arguments pass the method name and the type of the method parameters.
  • getMethods()— This method returns an array containing Method objects for all the public methods of the class even the inherited ones.
  • getDeclaredMethod(String name, Class. parameterTypes)— Using getDeclaredMethod() you can get a Method object for the specified method of the class (having any access modifier public, private, protected, default).
  • getDeclaredMethods()— This method returns an array containing Method objects for all the declared methods of the class including public, protected, default (package) access, and private methods, but excluding inherited methods.

How to invoke method using Java reflection API

Once you have a Method instance using any of the above mentioned methods, you can invoke method of the class by calling java.lang.reflect.Method.invoke().

First argument to the invoke method is the object instance on which this particular method is to be invoked i.e. object of the class where the method resides. If the method called is static, first argument should be null. Subsequent arguments are the method’s parameters.

In case underlying method throws an exception, it will be wrapped by an java.lang.reflect.InvocationTargetException.

Invoking class methods using Java reflection API example

As a preparation for the example code let’s have a class called TestClass.java with methods that are invoked using Java reflection API.

public class TestClass < public String appendString(String str1, String str2) < return str1+ " " +str2; >static int addValues(int a, int b) < return a+b; >private boolean compare(int a, int b) < return a >b; > >

Invoking instance method using Java reflection API example

If you have to invoke the public method appendString() of the given class then it can be done using the following method-

public void callMethod() < Classc = null; String result=""; try < // Getting Class instance c = Class.forName("org.netjs.prog.TestClass"); // Getting class object TestClass obj = new TestClass(); Method method = null; // getting method instance by passing method name and parameter types method = c.getDeclaredMethod("appendString", String.class, String.class); // invoking method result = (String)method.invoke(obj, "Hello", "World"); >catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) < // TODO Auto-generated catch block e.printStackTrace(); >System.out.println("Returned result is- " + result); >
Returned result is- Hello World

Invoking static method of a class

If you have to invoke a static method of a class then while calling the invoke method pass the first argument (which denotes the class object) as null.

public void callMethod() < Classc = null; int result = 0; try < // Getting Class instance c = Class.forName("org.netjs.prog.TestClass"); // Getting class object TestClass obj = new TestClass(); Method method = null; // getting method instance by passing method name and parameter types method = c.getDeclaredMethod("addValues", int.class, int.class); // invoking method result = (Integer)method.invoke(null, 20, 30); >catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) < // TODO Auto-generated catch block e.printStackTrace(); >System.out.println("Returned result is- " + result); >

Invoking private method using Java reflection API

You can even invoke the private method of the class using reflection in Java.

Using getDeclaredMethod() you can get the private method of the class. Once you have the method object you can use the setAccessible() method which is inherited from class java.lang.reflect.AccessibleObject to set the access for the private method as true at run time and then invoke it from another class.

public void callMethod() < Classc = null; boolean result = false; try < // Getting Class instance c = Class.forName("org.netjs.prog.TestClass"); // Getting class object TestClass obj = new TestClass(); Method method = null; // getting method instance by passing method name and parameter types method = c.getDeclaredMethod("compare", int.class, int.class); // Making method accessible method.setAccessible(true); // invoking private method of the class result = (Boolean)method.invoke(obj, 60, 30); >catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) < // TODO Auto-generated catch block e.printStackTrace(); >System.out.println("Returned result is- " + result); >

That’s all for this topic Invoke Method at Runtime Using Java Reflection API. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

Оцените статью