Java Reflection mechanism (my first blog post)

Source: Internet
Author: User

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.
Java Reflection (emission) mechanism: "When a program is run, it is allowed to change the program structure or variable type, which is called Dynamic language." From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language. But Java has a very prominent dynamic-related mechanism: Reflection, in Java, refers to the classes that we can load, detect, and use completely unknown during compilation at runtime. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods.
The Java Reflection mechanism provides the following functions: To determine the class to which any object belongs at run time, to construct an object of any class at run time, to determine the member variables and methods that any class has at run time, to invoke a method of any object at run time, and to generate a dynamic proxy. Sometimes we say that a language is highly dynamic, and sometimes we distinguish between dynamic and static techniques and practices. Our catchy dynamic bindings, dynamic binding (dynamiclinking), dynamic load (dynamically loading), and more. However, the term "dynamic" is not strictly and universally applicable strict definition, and sometimes even like object-oriented in the beginning of the field of programming, one person a number, each blowing the tune.
In general, the developer community speaks of dynamic language, which is broadly agreed to as a definition: "When a program is run, it is allowed to change the program structure or variable type, which is called Dynamic language." From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language.
Although Java is not a dynamic language under such definitions and classifications, it has a very prominent dynamic correlation mechanism: Reflection. This word means "reflection, image, reflection," which is used in Java to refer to the classes that we can load, detect, and use completely unknown during compilation. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods. This ability to "See Through Class" (the ability of the program to examine itself) is called introspection (introspection, vipassana, introspection). Reflection and introspection are the two terms that are often and are mentioned.
How can Java make the dynamic features described above? This is a far-reaching topic, and this article simply introduces some concepts. The whole space is mostly about reflection APIs, which is to let the reader know how to explore the structure of class, how to create a copy of an entity for a "class that knows the name at runtime", set a value for its fields, and call its methods.

1. Get the properties of an object

Java code
    1. public object getproperty (Object owner,  string fieldname)  THROWS EXCEPTION {  
    2.      class ownerclass = owner.getclass ();   
    3.    
    4.      field field = ownerclass.getfield (fieldName);  
    5.    
    6.      object property = field.get ( owner);   
    7.    
    8.      
    9. }  


Class Ownerclass = Owner.getclass (): Gets the class of the object.

Field field = Ownerclass.getfield (FieldName): Gets the properties of the class declaration through class.

object property = Field.get (owner): an instance of the attribute is obtained from the object, and if the property is non-public, the Illegalaccessexception is reported here.

2. Get static properties for a class

Java code
    1. public object getstaticproperty (string  Classname, string fieldname)   
    2.               THROWS EXCEPTION {  
    3.      class ownerclass = class.forname (className);   
    4.    
    5.      field field = ownerclass.getfield (fieldName);  
    6.    
    7.      object property = field.get ( Ownerclass);   
    8.    
    9.       RETURN PROPERTY;  
    10. }  



Class Ownerclass = Class.forName (className): First, the class is given.

Field field = Ownerclass.getfield (fieldName): As above, the properties of the class declaration are obtained by class.

Object property = Field.get (Ownerclass): Here is a bit different from the above because it is static, so it is taken directly from class.

3. Methods for executing an object

Java code
  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 = Ownerclass.getmethod (Methodname,argsclass);
  8. return Method.invoke (owner, args);
  9. }


Class Owner_class = Owner.getclass (): The object's class must be obtained first.

5~9: A class array of configuration parameters, as a condition for finding method.

Method method = Ownerclass.getmethod (MethodName, Argsclass): Gets the method to execute through an array of methodName and the argsclass of the arguments (the collection of parameter types in the method).

Method.invoke (owner, args): The parameter that executes the Method.invoke method is the object that executes the method, the owner, and the parameter array args, which can be understood as follows: The methods method with the parameter args in the owner object. The return value is object and is both the return value of the method.

4. Executing a static method of a class

Java code
  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 = Ownerclass.getmethod (Methodname,argsclass);
  9. return Method.invoke (null, args);
  10. }



The basic principle is the same as example 3, the difference is the last line, and an argument to invoke is NULL, because this is a static method and does not need to be run with an instance.

5. Create a new instance

Java code
  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 used here is to execute a constructor with parameters to create a new instance of the method. If no parameters are required, it can be implemented directly using Newoneclass.newinstance ().

Class Newoneclass = Class.forName (className): The first step is to get the Class of the instance to be constructed.

5~ Line 9th: Gets the class array of the arguments.

Constructor cons = Newoneclass.getconstructor (Argsclass): Gets the constructor.

Cons.newinstance (args): new instance.

6. Determine if an instance of a class

Java code
    1. Public boolean isinstance (Object obj, Class cls) {
    2. return cls.isinstance (obj);
    3. }


7. Get an element in the array

Java code
      1. public object Getbyarray (object array, int index) {
      2. return Array.get (Array,index);
      3. }


  

  

Java Reflection mechanism (my first blog post)

Related Article

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.