Application of Java reflection mechanism

Source: Internet
Author: User

This is through the reflection mechanism of Java to avoid repeated writing similar call Methods
  1. // Set data through the Reflection Method
  2. For (INT I = 0; I <grade_num; I ++ ){
  3. Method1 = getvaluemethod. setmethod (New fr0313dto (),
  4. "Minoritystunum" + (I + 1 ),
  5. New Class [] {string. Class });
  6. Method2 = getvaluemethod. setmethod (New fr0313dto (),
  7. "Girlstunum" + (I + 1 ),
  8. New Class [] {string. Class });
  9. Method3 = getvaluemethod. setmethod (New fr0313dto (),
  10. "Stunum" + (I + 1), new class [] {string. Class });
  11. Try {
  12. Method1.invoke (DTO, new object [] {string
  13. . Valueof (minoritystunum )});
  14. Method2.invoke (DTO, new object [] {string
  15. . Valueof (getintvalue (acadgirlmap
  16. . Get (gradeacadyear [I])});
  17. Method3.invoke (DTO, new object [] {string
  18. . Valueof (getintvalue (acadstumap
  19. . Get (gradeacadyear [I])});
  20. } Catch (illegalargumentexception e ){
  21. Log. Error (E );
  22. } Catch (illegalaccessexception e ){
  23. Log. Error (E );
  24. } Catch (invocationtargetexception e ){
  25. Log. Error (E );
  26. }
  27. }

The following describes how to assemble the set method. setmethod in getvaluemethod

  1. Public static method setmethod (Object object, string propertyname,
  2. Class [] partypes ){
  3. If (propertyname = NULL | propertyname. Length () = 0 ){
  4. Return NULL;
  5. }
  6. String propertynameupper = propertyname. substring (0, 1). touppercase ()
  7. + Propertyname. substring (1 );
  8. String methodname = "set" + propertynameupper;
  9. Method method = NULL;
  10. Try {
  11. Method = object. getclass (). getmethod (methodname, partypes );
  12. } Catch (securityexception e ){
  13. E. printstacktrace ();
  14. } Catch (nosuchmethodexception e ){
  15. E. printstacktrace ();
  16. }
  17. Return method;
  18. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: [email protected] and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.