Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to call a method using reflection

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use reflection to call methods", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use reflection to call methods.

Reflection invocation constructor

In addition to the inheritance relationship in a class, the most important operation is to deal with the structure in the class, and the structure in the class first needs to observe the use of the construction method. In fact, we have been exposed to the problem of construction methods when instantiating objects through reflection:

Instead of instantiating method: clazz.getDeclaredConstructor (). NewInstance ()

The constructor methods of all classes can be obtained directly through the Class class, which defines the following methods:

Get all constructors:

Public Constructor [] getDeclaredConstructors () throws SecurityException

Gets the specified constructor:

Public Constructor getConstructor () throws SecurityException

Get all constructors:

Public Constructor [] getConstructors () throws SecurityException

Gets the specified constructor:

Public Constructor getConstructor (Class... ParameterTypes) throws NoSuchMethodException, SecurityException

Example: modify the definition of the Person class

AbstractBase:

Public abstract class AbstractBase {public AbstractBase () {} public AbstractBase (String msg) {}}

Person:

Public class Person extends AbstractBase implements IChannelService,IMessageService {public Person () {} public Person (String name, int age) {}

Example: get construction

JavaAPIDemo

Public class JavaAPIDemo {public static void main (String [] args) {Class cls = Person.class;// get the Class object Constructor [] constructors = cls.getDeclaredConstructors () of the specified class; / / get all constructed for (Constructor cons: constructors) {System.out.println (cons);} / / execution result: public cn.mldn.vo.Person () / / public cn.mldn.vo.Person (java.lang.String,int)

What you get at this point is all the constructors in the class, but you can also get the construction of a specified parameter. For example, there are now two constructors in the Person class:

Modify Person:

Public class Person extends AbstractBase implements IChannelService,IMessageService {private String name;private int age;public Person () {} public Person (String name, int age) {this.name = name;this.age = age;} public String getName () {return name;} public void setName (String name) {this.name = name;} @ Overridepublic String toString () {return "name:" + this.name + ", age:" + this.age;}} "

At this point, call the parameter constructor in the Person class to instantiate the Person class object, and you must indicate the construction to be invoked, and then operate through the instantiation method provided in the Constructor class:

Public T newInstance (Object... Initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

Example: call the specified construction instantiated object

Import java.lang.reflect.Constructor;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Class cls = Person.class; Constructor constructor = cls.getConstructor (String.class, int.class); Object obj = constructor.newInstance ("Xiaoqiang", 78); System.out.println (obj); / / name: Xiaoqiang, age: 78}}

Although the program code itself allows developers to call parametric constructs, from an actual development point of view, it is best to use no-parameter constructs in all classes that use reflection, because such instantiation can achieve uniformity.

Reflection calls normal methods

When doing reflection processing, you can also get all the methods in the class through reflection, but you need to be reminded that if you want to call these methods through reflection, there must be a prerequisite: instantiated objects are provided in the class.

The following operations are provided in the Class class to get the method object:

Get all the methods:

Public Method [] getMethods () throws SecurityException

Get the specified method:

Public Method getMethod (String name, Class... ParameterTypes) throws NoSuchMethodException, SecurityException

Get all the methods of this class:

Public Method [] getDeclaredMethods () throws SecurityException

Get the specified method of this class:

Public Method getDeclaredMethod (String name, Class... ParameterTypes) throws NoSuchMethodException, SecurityException

Example: get all methods

Import java.lang.reflect.Method;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Class cls = Person.class; {Method methods [] = cls.getMethods (); / / get all methods (including methods in the parent class) for (Method met: methods) {System.out.println (met) }} System.out.println ("- unforgettable split line of April Fool's Day -") {/ / get this class method Method methods [] = cls.getDeclaredMethods (); for (Method met: methods) {System.out.println (met);}

Execution result:

However, it should be noted that the acquisition of method information at this time depends on the toString () method provided by the Method class, and in many cases, the display form of method information can be cobbled together by users.

Example: custom method information display

Import java.lang.reflect.Method;import java.lang.reflect.Modifier;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Class cls = Person.class; / / get the Class object of the specified class Method methods [] = cls.getMethods (); for (Method met:methods) {int mod=met.getModifiers (); / / the modifier System.out.print (Modifier.toString (mod) + ">) System.out.print (met.getReturnType (). GetName () + "); System.out.print (met.getName () +" ("); Class params [] = met.getParameterTypes (); / / get parameter type for (int x = 0; x

< params.length; x ++) {System.out.print(params[x].getName() + " " + "arg-" + x);if(x < params.length - 1) {System.out.println(","); } }System.out.print(")");class exp [] = met.getExceptionTypes();if(exp.length >

0) {System.out.print ("throws");} for (int x = 0; x < exp.length; x + +) {System.out.print (exp.getName ()); if (x < exp.length-1) {System.out.println (",");}} System.out.println (); / / line feed}

This code only needs to be clear about the structure of the method based on reflection, without much in-depth understanding, but there is a fatally important method in the Method class:

Public Object invoke (Object obj, Object... Args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException

Setter and getter methods are appended to the name property in the Person class.

Public class Person extends AbstractBase implements IChannelService,IMessageService {private String name;private int age;public Person () {} public Person (String name, int age) {this.name = name;this.age = age;} public String getName () {return name;} public void setName (String name) {this.name = name;} / / other operation codes slightly}

The call handling of the setter and getter methods in the Person class needs to be implemented through a reflection mechanism.

Example: implement the configuration of properties without importing the specified class development package

Public class JavaAPIDemo {public static void main (String [] args) throws Exception {Class cls = Class.forName ("cn.mladn.vo.Person"); / / get the Class object of the specified class / / String attribute = "name"; / / the class attribute to be operated String value = "Little Hadron"; / / the attribute content to be set / / 1. In any case, if you want to save the properties in the class or call the methods in the class, you must ensure that there is an instantiated object. Since the import package is not allowed, reflect instantiation Object obj = cls.getDeclaredConstructor (). NewInstance (); / / call no-parameter construction instantiation / / 2. If you want to make a method call, be sure to get the method name String setMethodName = "setName"; / / method name Method method= cls.getDeclaredMethodsetMethodName, String.class); / / get the specified method method.invoke (obj, value); / / equivalent to: Person object .setName (value); String getMethodName= "getName"; method=cls.getDeclaredMethod (getMethodName); / / getter has no parameter System.out.println (getMethod.invoke (obj);) / / equivalent to: Person object .getName ();}}

The overall form of using such operations will not produce any explicit class objects, and everything is handled by the reflection mechanism, which avoids the problem of coupling with a certain class.

At this point, I believe you have a deeper understanding of "how to use reflection to invoke methods". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report