Application notes of java reflection in practical work

Recently, I encountered such a problem in my work:

Make a test tool for all interfaces in a project, using Java Swing technology. The project has different versions, not all interfaces in all versions are the same, and the tool I make needs to be compatible with all versions.

Thus, such a problem is introduced:

If some interfaces do not exist in some versions, an error will be reported when performing this operation through the interface. Therefore, in order to be compatible with all versions, it is necessary to consider whether the method exists before calling the method. At the same time, in order not to throw exceptions during compilation, when calling the method

It also needs to be called through reflection. The specific implementation is as follows:

1、 Use reflection to determine whether the method exists

Parameter introduction:

(1) Obj: represents the object that calls a method

(2) Methodname: the name of the method to call

(3) Paratypes: parameter types required by the method (array if multiple)

Through this method, you can judge whether the methodname (parameter type) method you call through the obj object exists. If it does not exist, nosuchmethodexception will run

2、 Avoid compile time exceptions by calling methods through reflection

In the above code:

The first line: the object sysuser that calls the createbucket method

The second line: the parameter type array in the method, which is used to judge whether the method exists

The third line: judge whether the method exists by object, method name and parameter type array

Through the above three lines, the following tasks will be executed when the method exists. If it does not exist, an exception message will be prompted

Line 6: get the class of the object

Line 7: get the method object of the object. The parameters are the method name and the type corresponding to the parameters

Line 8: call createbucket method through method object reflection. The parameters are sysuser object and required parameter (value)

Through the above methods, compile time exceptions will not occur even if an interface in the object does not exist.

Seriously, this is the first time I have encountered java reflection problems in my project. It is necessary to record it!

summary

The above is all about the application notes of java reflection in practical work. I hope it will be helpful to you. Interested friends can continue to refer to this website:

Java reflection easy tutorial

What you need to know about java reflection mechanism

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>