Java: Reflection Basics

Source: Internet
Author: User
Tags function examples instance method

Java: Reflection BasicsIntroduce reflectionWhat is reflection?

A program capable of dynamically analyzing class capabilities is called reflection.

Reflection is a very powerful and complex mechanism.

class

During a program run, the Java Runtime system always maintains a type identity known as the runtime for all objects . This object tracks the class to which each object belongs. The virtual machine uses the information of the run-time class to choose the appropriate method to execute .

We can access this information through a dedicated Java class. The classes that hold this information are called class.

To obtain class information from an object:

=// get class name

There are two other ways to get class classes :

1. Call the static method forname to get the class name corresponding to the classes object.

String className = ' java.util.Date '= Class.forName (className);

2. Direct Access

Class CL1 =date. class  = Integer. class;

Attention:

  A virtual machine manages a class object for each type. Therefore , use = = To achieve two class object comparison operations .

ability to use reflection to analyze classesAPI function Examples
    • Getdeclaredfields (): Gets all the fields declared by the class or interface represented by such an object.
    • Getdeclaredmethods (): Obtain all methods declared by the class or interface represented by such an object, including public, protected, private, but not inherited.
    • getDeclaredConstructors(): Returns Constructor an array of objects that reflect all of the Class constructor methods for the class declaration represented by this object.
    • GetName (): Gets the name of the entity represented by this class.
using reflection to parse objects at run timeAPI function Examples
    • setaccessible (Boolean flag): Sets the accessible flag for the reflected object. True allows the object's private properties to be queried and set.
    • GetField (): Returns an Field object that reflects the Class specified public member field of the class or interface represented by this object.
    • Get (Object obj): Returns the field value represented by the Field object in the object.
    • Set (Object obj,object NewValue): Sets the field represented by the Field object in the Obj object with a new value.
Example Demo

call any method with reflectionAPI function Description
Invoke (Object obj,                     Object ... args)              throws Illegalaccessexception,                     IllegalArgumentException,                     InvocationTargetException
  • Invokes the Method underlying method represented by this object for the specified object with the specified argument. Individual parameters are automatically unpacked to match the basic parameters, and both the basic and reference parameters are subject to the method invocation transformation.
  • If the underlying method is static, the specified argument can be ignored obj . The parameter can be null.
  • If the underlying method requires a shape parameter of 0, the supplied args array can be 0 or null in length.
  • If the underlying method is an instance method, it is called using the dynamic method lookup, which is recorded in the 15.12.4.4 section of Java Language specification, Second Edition, and should be done in the case of overrides based on the runtime type of the target object.
  • If the underlying method is static and the class declaring the method has not been initialized, it will be initialized.
  • If the method completes normally, the value returned by the method is returned to the caller, and if the value is a base type, it is first wrapped appropriately in the object. However, if the type of the value is a set of basic types, the array element is not wrapped in the object, in other words, an array of the base type is returned. If the underlying method return type is void, the call returns NULL.
Parameters:
obj -Object from which the underlying method is invoked
args -parameters for method invocation
Return:
Use parameters args to obj Assign the result of the method represented on the object
Thrown:
IllegalAccessException -If this Method object enforces Java language access control, and the underlying method is inaccessible.
IllegalArgumentException -If the method is an instance method, and the specified object parameter is not an instance of the class or interface (or the subclasses or the implementation program) that declares the underlying method, if the number of arguments and parameters is not the same, if the package conversion of the base parameter fails; You cannot convert a parameter value to the corresponding formal parameter type through a method call transformation.
InvocationTargetException -if the underlying method throws an exception.
NullPointerException -If the specified object is null, and the method is an instance method.
ExceptionInInitializerError -If the initialization caused by this method fails

Java: Reflection Basics

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.