Java.lang.reflect

xiaoxiao2021-03-06  18

The reflection of Java is very interesting. A recently studied a package.

It is found that many repetitive code can be simplified using reflection.

For example, I have a simple bean, the structure is as follows:

Class testbean {

Private string userid;

PRIVATE STRING Password;

PRIVATE STRING YEAR;

Public getxxx ();

Public setxxx ();

.........

}

Usually the caller is often not tired when filling this class, how many getxxx () and setxxx () should be written, in fact, if the reflection is used, this problem is well resolved.

As an example of the usual use of the reflective class Method:

First I define an array to store the field names and types of the table of the database:

Private final static string [] FieldNames = {{"MQ_USERID", "int"}, {"mq_username", "string"}, {"mq_inbox_name", "string"}, {"mq_outbox_name", "string"} , {"MQ_RESPONSE_NAME", "String"}};

Then call in the method:

ResultSet RS;

IF (rs.next ()) {method INTMETHOD = ResultSet.class.getMethod ("getInt", new class [] {string.class}); method strmethod = ResultSet.class.getMethod ("getString", new class [] {String.class}); // cycle with reflection method to take the value of the corresponding field for (INT i = 0; I

}

转载请注明原文地址:https://www.9cbs.com/read-44248.html

New Post(0)