Java reflections invoke static method

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).

Читайте также:  Java system time in seconds

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

Источник

Java Reflection Invoke Static Method

This article will look at how we can use Java Reflection API to invoke a Static method. We will see the steps and the explanation with code. Let us first have a quick look at Reflection API.

Reflection in Java is a process of examining or modifying the behavior of a class at run time. Moreover, It is an API or Application Programming Interface having its use in debugging. It is also used in testing tools, with the primary focus on changing the runtime behavior of a class. In Java, The Package java.lang.Reflect provides the classes and interface to obtain reflective information about classes and objects.

Now, the task is to invoke a Static method using Reflection in Java. Consider this class StudentDetails:

Here, we have two static methods one gets the details of a student and one gives the total number of students. As you can see both are static methods and we have to invoke these two methods in our Main class or Controller and execute them without creating an Object of the Class.

Invoking Static Method

  • Create a Class Object: We create a Class Object of Type StudentDetails using the .class keyword.
  • Get The Method: Next, we get the required methods from the StudentDetails class with the Class Object we created. We use a Method object of class java.lang.reflect.Method. We invoke the getMethod() of the Class Object which returns the specified method of class as a Method Object.

The General Syntax is: public Method getMethod(String MethodName, ParameterType.class)

  • Invoke Method: After this, we invoke the static method using invoke() method of the Method object. The General Syntax: public Object invoke(Object ClassObject, Object Parameters)

Note: Here, as the method is static we don’t need a Class Object so the first argument is null, In Method Parameters, we typecast the parameter as Object Type for any Object type parameter. The Primitive data types are automatically passed as a Wrapper class Object.

Let us have a look at the implementation of the Main Class or StudentController in code.

Источник

Вызов статического метода с помощью Java Reflection API

Чтобы упростить демонстрацию и объяснение, давайте сначала создадим класс GreetingAndBye в качестве примера:

 public class GreetingAndBye     public static String greeting(String name)    return String.format("Hey %s, nice to meet you!", name);   >    private static String goodBye(String name)    return String.format("Bye %s, see you next time.", name);   >   > 

Класс GreetingAndBye выглядит довольно просто. Он имеет два статических метода, один публичный и один частный .

Оба метода принимают аргумент типа String и возвращают в качестве результата строку .

Теперь давайте вызовем два статических метода с помощью Java Reflection API. В этом руководстве мы рассмотрим код как методы модульного тестирования.

3. Вызов общедоступного статического метода​

Во-первых, давайте посмотрим, как вызвать общедоступный статический метод:

 @Test   void invokePublicMethod() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException    ClassGreetingAndBye> clazz = GreetingAndBye.class;   Method method = clazz.getMethod("greeting", String.class);    Object result = method.invoke(null, "Eric");    Assertions.assertEquals("Hey Eric, nice to meet you!", result);   > 

Следует отметить, что нам необходимо обрабатывать необходимые проверенные исключения , когда мы используем Reflection API.

В приведенном выше примере мы сначала получаем экземпляр класса, который мы хотим протестировать, который называется GreetingAndBye .

Получив экземпляр класса, мы можем получить объект общедоступного статического метода, вызвав метод getMethod .

Как только мы получим объект метода , мы можем вызвать его, просто вызвав метод вызова .

Стоит объяснить первый аргумент метода вызова . Если метод является методом экземпляра, первым аргументом является объект, из которого вызывается базовый метод.

Однако, когда мы вызываем статический метод, мы передаем null в качестве первого аргумента , поскольку статические методы не требуют экземпляра для вызова.

Наконец, если мы запустим тест, он пройдет.

3. Вызов частного статического метода​

Вызов частного статического метода очень похож на вызов общедоступного . Давайте сначала посмотрим на код:

 @Test   void invokePrivateMethod() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException    ClassGreetingAndBye> clazz = GreetingAndBye.class;   Method method = clazz.getDeclaredMethod("goodBye", String.class);   method.setAccessible(true);    Object result = method.invoke(null, "Eric");    Assertions.assertEquals("Bye Eric, see you next time.", result);   > 

Как видно из приведенного выше кода, когда мы пытаемся получить объект Method частного метода, мы должны использовать getDeclaredMethod вместо getMethod .

Более того, нам нужно вызвать method.setAccessible(true) для вызова приватного метода . Это попросит JVM подавить проверки контроля доступа для этого метода.

Таким образом, это позволяет нам вызывать закрытый метод. В противном случае будет возбуждено исключение IllegalAccessException .

Тест пройдет, если мы его выполним.

4. Вывод​

В этой короткой статье мы рассмотрели, как вызывать статические методы с помощью Java Reflection API.

Как всегда, полный код можно найти на GitHub .

Источник

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

Источник

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