Java reflection classic instance

Source: Internet
Author: User

Java provides a set of mechanisms to dynamically execute methods, constructor methods, and array operations. This mechanism is called reflection. Reflection mechanisms are the basis for implementation of many popular frameworks today, including spring and hibernate. The principle issue is not the focus of this Article. Next, let's learn about this wonderful mechanism in the instance.

1. Get the attributes of an object

 

Source code printing?
  1. Public object getproperty (Object owner, string fieldname) throws exception {
  2. Class ownerclass = owner. getclass ();
  3. Field field = ownerclass. getfield (fieldname );
  4. Object Property = field. Get (owner );
  5. Return property;
  6. }

Class ownerclass = owner. getclass (): obtains the class of the object.

Field field = ownerclass. getfield (fieldname): obtains the attribute declared by the class through the class.

Object Property = field. Get (owner): obtains the instance of this attribute through the object. If this attribute is not public, illegalaccessexception is reported here.

 

2. Obtain the static attributes of a class.

 

Source code printing?
  1. Public object getstaticproperty (string classname, string fieldname)
  2. Throws exception {
  3. Class ownerclass = Class. forname (classname );
  4. Field field = ownerclass. getfield (fieldname );
  5. Object Property = field. Get (ownerclass );
  6. Return property;
  7. }

Class ownerclass = Class. forname (classname): first obtain the class of this class.

Field field = ownerclass. getfield (fieldname): Same as above, get the attribute declared by class through class.

Object Property = field. Get (ownerclass): This is somewhat different from the above. Because this property is static, it is directly retrieved from the class of the class.

3. Execute the method of an object

 

Source code printing?
  1. Public object invokemethod (Object owner, string methodname, object [] ARGs) throws exception {
  2. Class ownerclass = owner. getclass ();
  3. Class [] argsclass = new class [args. Length];
  4. For (INT I = 0, j = args. length; I <j; I ++ ){
  5. Argsclass [I] = ARGs [I]. getclass ();
  6. }
  7. Method method = ownerclass. getmethod (methodname, argsclass );
  8. Return method. Invoke (owner, argS );
  9. }

Class owner_class = owner. getclass (): first, you must obtain the class of this object.

5 ~ Row 9: configure the class array of the parameter as the condition for finding the method.

Method method = ownerclass. getmethod (methodname, argsclass): Obtain the method to be executed through the method name and the class array of the parameter.

Method. Invoke (owner, argS): executes this method. The parameters of the invoke method are the objects that execute this method, and the parameter arrays. The returned value is an object and the return value of this method.

4. Execute the static method of a class

 

Source code printing?
  1. Public object invokestaticmethod (string classname, string methodname,
  2. Object [] ARGs) throws exception {
  3. Class ownerclass = Class. forname (classname );
  4. Class [] argsclass = new class [args. Length];
  5. For (INT I = 0, j = args. length; I <j; I ++ ){
  6. Argsclass [I] = ARGs [I]. getclass ();
  7. }
  8. Method method = ownerclass. getmethod (methodname, argsclass );
  9. Return method. Invoke (null, argS );
  10. }

The basic principle is the same as that of instance 3. The difference is that the last line, one of the parameters of invoke is null, because this is a static method and does not need to be run by the instance.

 

5. Create an instance

 

Source code printing?
  1. Public object newinstance (string classname, object [] ARGs) throws exception {
  2. Class newoneclass = Class. forname (classname );
  3. Class [] argsclass = new class [args. Length];
  4. For (INT I = 0, j = args. length; I <j; I ++ ){
  5. Argsclass [I] = ARGs [I]. getclass ();
  6. }
  7. Constructor cons = newoneclass. getconstructor (argsclass );
  8. Return cons. newinstance (ARGs );
  9. }

The method described here is to execute a constructor with parameters to create an instance. If no parameter is required, you can use newoneclass. newinstance () directly.

Class newoneclass = Class. forname (classname): the first step is to obtain the class of the instance to be constructed.

5th ~ Row 9th: obtains the class array of the parameter.

Constructor cons = newoneclass. getconstructor (argsclass): Obtain the constructor.

Cons. newinstance (ARGs): creates an instance.

6. Determine whether it is an instance of a class

 

Source code printing?
  1. Public Boolean isinstance (Object OBJ, class CLs ){
  2. Return Cls. isinstance (OBJ );
  3. }

7. Obtain an element in the array.

 

Source code printing?
  1. Public object getbyarray (Object array, int index ){
  2. Return array. Get (array, index );
  3. }

Complete source code:

 

Source code printing?
  1. Import java. Lang. Reflect. array;
  2. Import java. Lang. Reflect. constructor;
  3. Import java. Lang. Reflect. field;
  4. Import java. Lang. Reflect. method;
  5. /**
  6. * Java reflection cookbook
  7. *
  8. * @ Author Michael Lee
  9. * @ Since 2006-8-23
  10. * @ Version 0.1a
  11. */
  12. Public class reflection {
  13. /**
  14. * Obtain the public attributes of an object.
  15. *
  16. * @ Param owner, fieldname
  17. * @ Return this property object
  18. * @ Throws exception
  19. *
  20. */
  21. Public object getproperty (Object owner, string fieldname) throws exception {
  22. Class ownerclass = owner. getclass ();
  23. Field field = ownerclass. getfield (fieldname );
  24. Object Property = field. Get (owner );
  25. Return property;
  26. }
  27. /**
  28. * Obtain a static public attribute
  29. *
  30. * @ Param classname Class Name
  31. * @ Param fieldname: attribute name
  32. * @ Return this property object
  33. * @ Throws exception
  34. */
  35. Public object getstaticproperty (string classname, string fieldname)
  36. Throws exception {
  37. Class ownerclass = Class. forname (classname );
  38. Field field = ownerclass. getfield (fieldname );
  39. Object Property = field. Get (ownerclass );
  40. Return property;
  41. }
  42. /**
  43. * Execute an object Method
  44. *
  45. * @ Param owner
  46. * Object
  47. * @ Param methodname
  48. * Method name
  49. * @ Param ARGs
  50. * Parameters
  51. * @ Return method Return Value
  52. * @ Throws exception
  53. */
  54. Public object invokemethod (Object owner, string methodname, object [] ARGs)
  55. Throws exception {
  56. Class ownerclass = owner. getclass ();
  57. Class [] argsclass = new class [args. Length];
  58. For (INT I = 0, j = args. length; I <j; I ++ ){
  59. Argsclass [I] = ARGs [I]. getclass ();
  60. }
  61. Method method = ownerclass. getmethod (methodname, argsclass );
  62. Return method. Invoke (owner, argS );
  63. }
  64. /**
  65. * Execute some static methods.
  66. *
  67. * @ Param classname
  68. * Class Name
  69. * @ Param methodname
  70. * Method name
  71. * @ Param ARGs
  72. * Parameter Array
  73. * @ Return the result returned by the execution Method
  74. * @ Throws exception
  75. */
  76. Public object invokestaticmethod (string classname, string methodname,
  77. Object [] ARGs) throws exception {
  78. Class ownerclass = Class. forname (classname );
  79. Class [] argsclass = new class [args. Length];
  80. For (INT I = 0, j = args. length; I <j; I ++ ){
  81. Argsclass [I] = ARGs [I]. getclass ();
  82. }
  83. Method method = ownerclass. getmethod (methodname, argsclass );
  84. Return method. Invoke (null, argS );
  85. }
  86. /**
  87. * Create an instance
  88. *
  89. * @ Param classname
  90. * Class Name
  91. * @ Param ARGs
  92. * Constructor Parameters
  93. * @ Return the newly created instance
  94. * @ Throws exception
  95. */
  96. Public object newinstance (string classname, object [] ARGs) throws exception {
  97. Class newoneclass = Class. forname (classname );
  98. Class [] argsclass = new class [args. Length];
  99. For (INT I = 0, j = args. length; I <j; I ++ ){
  100. Argsclass [I] = ARGs [I]. getclass ();
  101. }
  102. Constructor cons = newoneclass. getconstructor (argsclass );
  103. Return cons. newinstance (ARGs );
  104. }
  105. /**
  106. * Is it a class instance?
  107. * @ Param OBJ instance
  108. * @ Param CLS class
  109. * @ Return if obj is an instance of this type, true is returned.
  110. */
  111. Public Boolean isinstance (Object OBJ, class CLs ){
  112. Return Cls. isinstance (OBJ );
  113. }
  114. /**
  115. * Obtain an element in the array.
  116. * @ Param Array
  117. * @ Param Index
  118. * @ Return returns the value of the index component in the specified array object.
  119. */
  120. Public object getbyarray (Object array, int index ){
  121. Return array. Get (array, index );
  122. }
  123. }

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: info-contact@alibabacloud.com 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.