JAVA reflection mechanism and application example

Source: Internet
Author: User

JAVA reflection mechanism is a key feature of Java as a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain internal information about any class with a known name through Reflection APIs at runtime, including its modifiers (such as public, private, static, etc.), superclass (such as Object), interfaces (such as Cloneable), also includes all information about fields and methods, and CALLS methods of any object at runtime; generates a dynamic proxy. Next, let's take a look at the main Reflection APIs Code. The Code has corresponding annotations.
 
Java code
Import java. lang. reflect. Array;
Import java. lang. reflect. Constructor;
Import java. lang. reflect. Field;
Import java. lang. reflect. InvocationTargetException;
Import java. lang. reflect. Method;
Import java. lang. reflect. Modifier;
 
Public class Goods
{
Private String id;
Private double price;
 
Public Goods (){
System. out. println ("it is a pen ");
}

Public Goods (String s1, String s2 ){
System. out. println (s1 + "*" + s2 );
}

Public String getId ()
{
System. out. println (id );
Return id;
}
Public void setId (String id)
{
This. id = id;
}
Public String addName (String str1, String str2 ){
Return str1 + str2;
}
/**
* @ Throws ClassNotFoundException
* @ Throws IllegalAccessException
* @ Throws InstantiationException
* @ Throws NoSuchMethodException
* @ Throws SecurityException
* @ Throws InvocationTargetException
* @ Throws IllegalArgumentException
* @ Throws NoSuchFieldException
* @ Function Description
* @ Input parameters
* @ Feedback value
*/
Public static void main (String [] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, expiration, InvocationTargetException, NoSuchFieldException
{
// TODO Auto-generated method stub
String str = "com. xtlh. sinye. Goods ";
Class c = Class. forName (str );
Object obj = c. newInstance (); // initialize a Goods Object

/**
* // The setId () method is called to set the attribute value. Class [] is used for the type and Object [] is used for the parameter.
*/
Method m = c. getMethod ("setId", new Class [] {Class. forName ("java. lang. String ")});
M. invoke (obj, new Object [] {"it's apple "});
System. out. println ("---------------------------------------------------------------------");

/**
* // Here, the getId () method is called to obtain the attribute value.
*/
M = c. getMethod ("getId", new Class [] {});
M. invoke (obj, new Object [] {});
System. out. println ("---------------------------------------------------------------------");

/**
* // Obtain the method declared in the class
*/
Method me [] = c. getDeclaredMethods ();
For (int I = 0; I <me. length; I ++ ){
System. out. println ("method [" + I + "] =" + me [I]. toString ());
}
System. out. println ("---------------------------------------------------------------------");

/**
* // Simulate the instanceof Operator
*/
Boolean b1 = c. isInstance (new Integer (34 ));
System. out. println ("Goods is a instance of Integer? "+ B1 );
Boolean b2 = c. isInstance (new Goods (); // The construction method without parameters is called here.
System. out. println ("Goods is a instance of Goods? "+ B2 );
System. out. println ("---------------------------------------------------------------------");

/**
* // Find out the class method, class name, class method parameters, class method return type
*/
Method med [] = c. getDeclaredMethods ();
Method med1 [] = c. getMethods (); // It can be seen from the literal meaning. Here we can find all the methods, that is, we can find the inherited methods.
For (int I = 0; I <med. length; I ++ ){
Method mee = med [I];
System. out. println ("method #" + I + "name =" + mee. getName ());
System. out. println ("declaring class =" + mee. getDeclaringClass ());
// Method parameter type
Class pvec [] = m. getParameterTypes ();
For (int j = 0; j <pvec. length; j ++ ){
System. out. println ("parameter #" + j + "=" + pvec [j]);
}
// Method exception
Class evec [] = m. getExceptionTypes ();
For (int j = 0; j <evec. length; j ++ ){
System. out. println ("exception #" + j + "" + evec [j]);
}
// Return type of the Method
System. out. println ("return type =" + mee. getReturnType ());
}
System. out. println ("---------------------------------------------------------------------");

/**
* // Obtain the class Constructor
*/
Constructor ctorlist [] = c. getDeclaredConstructors ();
For (int I = 0; I <ctorlist. length; I ++ ){
Constructor cons = ctorlist [I];
System. out. println ("Constructor #" + I + "name =" + cons. getName ());
Class [] consParaType = cons. getParameterTypes (); // obtain the parameter type of the constructor.
If (consParaType. length = 0 ){
System. out. println ("Constructor have no parameters ");
} Else {
For (int j = 0; j <consParaType. length; j ++ ){
System. out. println ("Constructor Parameter type #" + j + "name =" + consParaType [j]);
}
}
}
System. out. println ("---------------------------------------------------------------------");

/**
* // Obtain the attributes of a class
*/
Field fieldlist [] = c. getDeclaredFields ();
For (int I = 0; I <fieldlist. length; I ++ ){
Field field = fieldlist [I];
System. out. println ("Filed #" + I + "name =" + field. getName (); // attribute name
System. out. println ("Filed #" + I + "type =" + field. getType (); // attribute type

Int mod = field. getModifiers ();
System. out. println ("modifiers =" + Modifier. toString (mod); // attribute Modifier private/public/protected
}
System. out. println ("---------------------------------------------------------------------");

/**
* // Execute the method based on the method name
*/
Class cls = Class. forName ("com. xtlh. sinye. Goods ");
Class partypes [] = new Class [2];
Partypes [0] = String. class; // more types of Long. TYPE Integer. TYPE, or use Long. class, Integer. class
Partypes [1] = Class. forName ("java. lang. String ");
Method meth = cls. getMethod ("addName", partypes );
Goods goods = new Goods ();
Object arglist [] = new Object [2];
Arglist [0] = new String ("love ");
Arglist [1] = new String ("grape ");
Object retobj = meth. invoke (goods, arglist );
String retval = (String) retobj;
System. out. println (retval );
System. out. println ("---------------------------------------------------------------------");

/**
* Create an object. Find the corresponding constructor Based on the specified parameter type and execute it to create a new object instance. This method can be used to dynamically create objects while the program is running, rather than creating objects during compilation, which is very valuable.
*/
Class clss = Class. forName ("com. xtlh. sinye. Goods ");
Class partypess [] = new Class [2];
Partypess [0] = String. class;
Partypess [1] = String. class;
Constructor ct = clss. getConstructor (partypess );
Object arglists [] = new Object [2];
Arglists [0] = new String ("hello ");
Arglists [1] = new String ("orange ");
Object retobjs = ct. newInstance (arglists );
System. out. println ("---------------------------------------------------------------------");

/**
* // Change the attribute value
*/
Class ccc = Class. forName ("com. xtlh. sinye. Goods ");
Field counter = ccc. getDeclaredField ("price ");
Goods goods1 = new Goods ();
System. out. println ("price =" + goods1.price );
Criteria. setDouble (goods1, 25.0 );
System. out. println ("price =" + goods1.price );
System. out. println ("---------------------------------------------------------------------");

/**
* // Simply use an array, create a String array of 10 units of length, assign a value to the String at 5th locations, and finally obtain and print the String from the array.
*/
Class linoleic = Class. forName ("java. lang. String ");
Object arr = Array. newInstance (linoleic, 10 );
Array. set (arr, 5, "hello Watermelon ");
String s = (String) Array. get (arr, 5 );
System. out. println (s );
System. out. println ("---------------------------------------------------------------------");

/**
* // Use a complex array. In this example, an integer array of 5x10x15 is created, assign a value of 37 to the element in [3] [5] [10. Note that multi-dimensional arrays are actually arrays. For example, after the first Array. get, arrobj is an Array of 10x15. Then obtain an element, that is, an Array with a length of 15, and assign a value to its 10th elements using Array. setInt.
Note that the type of the array is dynamic when it is created, and the type is unknown during compilation.
*/
Int dims [] = new int [] {5, 10, 15 };
Object array = Array. newInstance (Integer. TYPE, dims );
Object arrobj = Array. get (array, 3 );
Class cl = arrobj. getClass (). getComponentType ();
System. out. println (cl );
Arrobj = Array. get (arrobj, 5 );
Array. setInt (arrobj, 10, 37 );
Int arrcast [] [] [] = (int [] [] []) array;
System. out. println (arrcast [3] [5] [10]);
}
 
}

Author "xSTARx"
 

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.