Java reflection mechanism

Source: Internet
Author: User

1. concept:

All attributes and methods of the class can be known to any class during runtime; every method and attribute of any object can be called; this kind of dynamic acquisition and calling function is called the reflection mechanism of Java language.

2. Implementation

Java reflection-related APIs in the packageJava. Lang. ReflectMedium

Member Interface This interface can be used to obtain information about constructors of class members (fields or methods.
Accessibleobject class This class is the basic class for field objects, method objects, and constructor objects. It provides the ability to mark reflected objects as canceling the default Java language access control check during use.
Array class This class provides methods to dynamically generate and access Java arrays.
Constructor class Provides information about the constructor of a class and the constructor interface of the class.
Field Class Provides information about the domain of a class and the interface of the region class.
Method class Provides information about a class method and interfaces of the class method.
Modifier class Provides static methods and constants to decode class and member access modifiers.
Proxy class

Provides static methods to dynamically generate proxy classes and class instances.

1)Obtains the class object of a class.

An instance of the class indicates a running Java application.ProgramClass and interface. There are multiple methods to obtain class objects of a class (Here we use the Boolean class as an example ):

Call getclass

Boolean var1 = true;

Class <?> Classtype2 = var1.getclass ();

System. Out. println (classtype2 );

Output: Class java. Lang. Boolean

Use. Class syntax

Class <?> Classtype4 = Boolean. Class;

System. Out. println (classtype4 );

Output: Class java. Lang. Boolean

Use static method class. forname ()

Class <?> Classtype5 = Class. forname ("Java. Lang. boolean ");

System. Out. println (classtype5 );

Output: Class java. Lang. Boolean

Use the type Syntax of primitive Wrapper Classes

The returned native type is different from that returned by Boolean. Class.

Class <?> Classtype3 = Boolean. type;

System. Out. println (classtype3 );

Output: Boo

2) Obtain fields of the class

You can obtain an attribute of a class through the reflection mechanism, and then change the attribute value corresponding to an instance of the class. The Java class <t> class provides several methods to obtain class attributes.

PublicFieldGetfield (StringName) Returns a Field object that reflects the specified public member fields of the class or interface represented by this class object.
PublicField[] Getfields () Returns an array containing some field objects. These objects reflect all accessible public fields of the class or interface represented by this class object.
PublicFieldGetdeclaredfield (StringName) Returns a Field object that reflects the declared fields specified by the class object or interface.
PublicField[] Getdeclaredfields () Return

3) obtain the method of the class

Obtain a method of a class through the reflection mechanism, and then call the method corresponding to an instance of the class. Class <t> provides several methods to obtain the class.

PublicMethodGetmethod (StringName,Class<?>... Parametertypes) Returns a method object that reflects the specified public member methods of the class or interface represented by this class object.
PublicMethod[] Getmethods ()

Returns an array containing some method objects. These objects reflect the classes or interfaces represented by this class object.

Includes the Public Member Methods declared by the class or interface and those classes or interfaces inherited from the superclass and superinterfaces.

PublicMethod Getdeclaredmethod (StringName,Class<?>... Parametertypes) Returns a method object that reflects the declared methods specified by the class object or interface.
PublicMethod[] Getdeclaredmethods ()

Returns an array of the method object. These objects reflect all the methods declared by the class object or interface,

Includes public, protected, default (Package) Access, and private methods, but does not include inherited methods

4) obtain the constructor of the class

get the constructor of a class through the reflection mechanism, and then call the constructor to create an instance of the class. The class class provides several methods to obtain the class constructor.

PublicConstructor<T> Getconstructor (Class<?>... Parametertypes) Returns a constructor object that reflects the specified public constructor of the Class Object.
PublicConstructor<?> [] Getconstructors () Returns an array containing certain constructor objects. These objects reflect all the common constructor methods of the classes represented by this class object.
PublicConstructor<T> Getdeclaredconstructor (Class<?>... Parametertypes) Returns a constructor object that reflects the specified constructor of the class object or interface.
PublicConstructor<?> [] Getdeclaredconstructors ()

Returns an array of constructor objects that reflect all constructor methods of class declarations represented by this class object.

They are public, protected, default (Package) Access, and private constructor

5) create a class instance

There are several ways to create a new class instance through the reflection mechanism

Call ctor without independent variable

1. Call the newinstance method of the Class Object of the class. This method calls the default constructor of the object. If no default constructor exists, the call fails.

Class <?> Classtype = extendtype. Class;

Object inst = classtype. newinstance ();

System. Out. println (insT );

Output:

Type: default constructor

Extendtype: default constructor

Com. Quincy. extendtype @ d80be3

 

2. Call the newinstance method of the default constructor object

Class <?> Classtype = extendtype. Class;

Constructor <?> Constructor1 = classtype. getconstructor ();

Object inst = constructor1.newinstance ();

System. Out. println (insT );

Output:

Type: default constructor

Extendtype: default constructor

Com. Quincy. extendtype @ 1006d75

Call the ctor with Parameters

3. Call the newinstance method with the constructor object

Constructor <?> Constructor2 =

Classtype. getdeclaredconstructor (Int. Class, String. Class );

Object inst = constructor2.newinstance (1, "123 ");

System. Out. println (insT );

Output:

Type: default constructor

Extendtype: constructor with Parameters

Com. Quincy. extendtype @ 15e83f9

 

6) Call Class Functions

Obtain the class method object through reflection and call the field invoke method to call the function.

7) set/obtain the class property value

Obtains the Field object of the class through reflection, and calls the field method to set or obtain the value.

3.Code

JavaThe reflection mechanism mainly provides the following functions:Determine the class to which any object belongs at runtime; construct the object of any class at runtime; and judge the member variables and methods of any class at runtime; call methods of any object at runtime; generate dynamic proxy.
1)Obtains the attributes of an object.

 
PublicObject getproperty (Object owner, string fieldname)ThrowsException
{
Class ownerclass = owner. getclass ();
Field field = ownerclass. getfield (fieldname );
Object Property = field. Get (owner );
ReturnProperty;
}

2)Obtains the static attributes of a class.

PublicObject getstaticproperty (string classname, string fieldname)ThrowsException
{
Class ownerclass = Class. forname (classname );
Field field = ownerclass. getfield (fieldname );
Object Property = field. Get (ownerclass );
ReturnProperty;
}

3)Method for executing an object

PublicObject invokemethod (Object owner, string methodname, object [] ARGs)ThrowsException
{
Class ownerclass = owner. getclass ();
Class [] argsclass =NewClass [args. Length];
For(IntI = 0, j = args. length; I <j; I ++)
{
Argsclass [I] = ARGs [I]. getclass ();
}
Method method = ownerclass. getmethod (methodname, argsclass );
ReturnMethod. Invoke (owner, argS );
}

4)Execute static methods of a class

PublicObject invokestaticmethod (string classname, string methodname, object [] ARGs)ThrowsException
{
Class ownerclass = Class. forname (classname );
Class [] argsclass =NewClass [args. Length];
For(IntI = 0, j = args. length; I <j; I ++)
{
Argsclass [I] = ARGs [I]. getclass ();
}
Method method = ownerclass. getmethod (methodname, argsclass );

ReturnMethod. Invoke (Null, ArgS );
}

Basic Principles and Examples3Same, the difference is the last line,InvokeA parameter of isNullBecause this is a static method, you do not need to use the instance to run.


5)Create an instance

PublicObject newinstance (string classname, object [] ARGs)ThrowsException
{
Class newoneclass = Class. forname (classname );
Class [] argsclass =NewClass [args. Length];

For(IntI = 0, j = args. length; I <j; I ++)
{
Argsclass [I] = ARGs [I]. getclass ();
}
Constructor cons = newoneclass. getconstructor (argsclass );

ReturnCons. newinstance (ARGs );
}

The method described here is to execute a constructor with parameters to create an instance. You can directly useNewoneclass. newinstance ().

6)Determines whether it is an instance of a class.

Public BooleanIsinstance (Object OBJ, class CLs)
{
ReturnCls. isinstance (OBJ );
}

7)Obtain an element in the array.

 
PublicObject getbyarray (Object array,IntIndex)
{
ReturnArray. Get (array, index );
}

 

4. A specific demo

Class ownerclass = Class. forname ("com. Test. Demo. Scroll. scrolllayout"); Method methodset= Ownerclass. getmethod ("setmscrollx", Integer. type); methodset. Invoke (mycustomlayout,256); Method methodget= Ownerclass. getmethod ("getmscrollx");IntM =(Integer) methodget. Invoke (mycustomlayout); Method methodstop= Ownerclass. getmethod ("handlestop"); Methodstop. Invoke (mycustomlayout); log. I ("CV", "m =" + M );

 

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.