Reflection mechanism of Java core class library

Source: Internet
Author: User

Tag: java.awt represents the throw variable parameter for dynamic Get CEP class object row

1: What is the reflection mechanism?  2: Reflection mechanism what can it do? 3: What is the API corresponding to the reflection mechanism?

1): Get the fully qualified name (full package name) and class name of an object by reflection mechanism;

2): Instantiate class object

3): Gets the parent class of the object and the implemented interface

4): Gets all the methods in the class or a single method

5): Call method with Reflection && invoke static method with reflection

6): Call array parameters using reflection

7): Use reflection to copy arrays dynamically

7): Gets all the constructors in a class, gets a single constructor with no arguments, gets the constructor with parameters

8): Call the constructor with reflection----> Create Object

9): Dynamically Load resource files

1. What is a reflection mechanism

The reflection mechanism is in the running state, for any class, can know all the properties and methods of the class, for any one object,

Can call its methods and properties, which dynamically acquires methods and properties, and dynamically invokes the functions of methods and properties , called the Java Reflection mechanism.

2. Reflection mechanism what it can do

The reflection mechanism mainly provides the following functions:

1: At run time, determine the class to which any object belongs.

2: Constructs an object of any class at run time.

3: At run time, determine the member variables and methods that any one class has.

4: At run time, arbitrarily call a method in a class.

5: Generate dynamic proxy.

5. What is the API for the reflection mechanism? Gets the fully qualified name of an object by an object (full package name)

Package Name: Classinstance class Name: methodd

private static void GetName () {Class claz=methodd.class;//gets the class of the object string Classname=claz.getname (); System.out.println (classname);//Print out: classinstance.methodd}

Instantiating a Class object
Package Net.xsoftlab.baike;public class Testreflect {public    static void Main (string[] args) throws Exception {        C lass<?> class1 = null;        Class<?> class2 = null;        Class<?> CLASS3 = null;        This form is generally used        class1 = Class.forName ("Net.xsoftlab.baike.TestReflect");        Class2 = new Testreflect (). GetClass ();        CLASS3 = Testreflect.class;        System.out.println ("Class name   " + class1.getname ());        System.out.println ("Class name   " + class2.getname ());        System.out.println ("Class name   " + class3.getname ());}    }
Gets the object's parent class and the implemented interface
Package Classinstance;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import java.io.serializable;//gets the parent class and implements the interface public class Getparentandinterface implements Serializable,actionlistener {public static void Main (string[] args) {class<?> claz=getparentandinterface.class;//Gets the object//Gets the parent class//returns the entity represented by this class (class, The class of the superclass of the interface, base type, or void). Class<?>parent=claz.getsuperclass (); SYSTEM.OUT.PRINTLN (parent);//Print Parents: Class java.lang.object//gets all the implementation interfaces//Getinterfaces () in the class to determine the interface that this object represents for the implementation of the class or interface. Class<?>[] Interface=claz.getinterfaces (); for (class<?> class1:interface) {System.out.println (Class1);}} public void actionperformed (ActionEvent e) {}}
Using reflection to invoke a method
Package Classinstance;import java.lang.reflect.method;//Using Reflection Call method class Invokeclass {public void MethodOne () { System.out.println ("Call a method without parameters!") ");} public void Methodtwo (String name) {System.out.println ("call a method with a parameter!") "+ name);} private string Methodthree (string name, int age) {System.out.println ("call method with a private two parameter!") "+ name +", "+ age"; return name + "," + Age;}} public class Methodinvokedemo {public static void main (string[] args) throws Exception {//Get class object class<invokeclass> C Lazz = invokeclass.class;//gets Method MD = Clazz.getmethod ("MethodOne"); Object DoWork = Md.invoke (Clazz.newinstance ()) ;//invoke (); System.out.println (DoWork);//Call the method with the parameter methods MD1 = Clazz.getmethod ("Methodtwo", String.class); Object dowork1 = Md1.invoke (Clazz.newinstance (), "Zhang San");//invoke (); System.out.println (DOWORK1);//Call private with two parameters method MD2 = Clazz.getdeclaredmethod ("Methodthree", String.class, Int.class) md2.setaccessible (TRUE);//Set accessible Private member Object DOWORK2 = Md2.invoke (Clazz.newinstance (), "Zhang San",)//invoke ( ); System.out.priNtln (DOWORK2); 

Calling a static method using reflection
Method md3 = Clazz.getdeclaredmethod ("Methodthree", String.class, Int.class);
Md3.setaccessible (TRUE);//Set Accessible private members
Object DOWORK3 = Md3.invoke (null, "Zhang San");//invoke ();
System.out.println (DOWORK3);}}

Use reflection to invoke array parameters (case 1: Array element type number basic type Case 2: Array element type is reference type)

Package Classinstance;import Java.lang.reflect.method;import java.util.arrays;class Method2 {public static void DoWork (int[] arr) {System.out.println ("DoWork was called" + arrays.tostring (arr));} public static void Dowork2 (string[] arr) {System.out.println ("Dowork2 was called" + arrays.tostring (arr));}} public class MethodInvokeDemo2 {//Use reflection call array parameter (variable parameter) public static void main (string[] args) throws Exception {class< method2> clazz = method2.class;//Case 1: Array element type number Basic Type method MD = Clazz.getmethod ("DoWork", Int[].class);//md.invoke ( NULL, 1,2,3,4,5,6); Error//object dw=md.invoke (null, New int[]{1,2,3,4,5,6}), Object DW = Md.invoke (null, new object[] {NE W int[] {1, 2, 3, 4, 5, 6}}); SYSTEM.OUT.PRINTLN (DW);//Case 2: Array element type is reference type method md1 = Clazz.getmethod ("Dowork2", String[].class);//md.invoke (NULL, New string[]{"A", "B", "C"}), Errorobject DW1 = Md1.invoke (null, new object[] {new string[] {"A", "B", "C"}}); System.out.println (DW1);}}

Dynamic copying of arrays using the reflection mechanism
Package Classinstance;import Java.lang.reflect.array;import java.util.arrays;//Use the reflection mechanism to dynamically copy the array public class Arraydemo { public static void Main (string[] args) {int[] src = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};int[] dest = new INT[10]; System.out.println (arrays.tostring (SRC)); Arraycopy (SRC, 2, dest, 3, 5); System.out.println (arrays.tostring (dest));} public static void Arraycopy (object src, int srcpos, object dest, int destpos, int length) {//source array and destination array must be array type if (!src.getc Lass (). IsArray () | | !dest.getclass (). IsArray ()) {throw new Arraystoreexception ("Source array and destination array is not an array type");} Source and destination arrays cannot be nullif (src = = NULL | | dest = = NULL) {throw new NullPointerException ("Source array and destination array cannot be null");} The array type of the source array and the destination array must be consistent if (Src.getclass (). Getcomponenttype ()! = Dest.getclass (). Getcomponenttype ()) {throw new Arraystoreexception ("The source array and the target array element types are inconsistent");} Source array and destination array do not want to index out of bounds if (Srcpos < 0 | | Destpos < 0 | | Length < 0 | | Srcpos + length > array.getlength (src) | | destpo s + length > array.getlength (dest)) {throw new IndexoutoFboundsexception ("Index Out of Bounds");} Gets the element that needs to be copied for (int index = SRCPOS; index < Srcpos + length; index++) {//To target array element object val = array.get (src, index); Array.set (dest, Destpos, Val);d estpos++;}}}

Get all the methods in a class or a single method
Package Classinstance;import Java.lang.reflect.method;class methodd {public void method1 () {}public void Method2 (String Name) {}private string method3 (string name, int age) {return name + ', ' + Age;}} public class Getmethoddemo {private static Getmethoddemo class2;//use reflection to get a method in a class public static void Main (string[] args) throw S Exception {getAll (); GetOne (); GetName ();} Gets the fully qualified name of an object by an object (full package name) private static void GetName () {Class Claz = methodd.class;//gets the class of the object string classname = Claz.getname (); System.out.println (classname);//Print out: classinstance.methodd}//Gets the specified method in the class private static void GetOne () throws Exception {class<methodd> Clasz = methodd.class;//Gets the class without parameters method MD = Clasz.getmethod ("method1");// Gets the method specified with a parameter in the class methods md1 = Clasz.getmethod ("Method2", string.class);//Gets the class private specifies a method with two parameters methods MD2 = Clasz.getdeclaredmethod ("Method3", String.class, Int.class); System.out.println (MD2);} private static void GetAll () {//Gets all methods in the class class<methodd> Clasz = methodd.class;/* * Returns an array of method objects that are reversedAll methods declared by the class or interface represented by this class object, * include public, protected, default (package) access, and private methods, but do not include inherited methods. */method[] MD = Clasz.getdeclaredmethods (); System.out.println (md.length); for (method Method:md) {System.out.println (method);}}}

Gets all constructors in a class, gets a single constructor with no arguments, gets the constructor with parameters
Package Classinstance;import Java.lang.reflect.constructor;class User {public user () {}public user (String name) {} Private User (String name, int age) {}}//Gets the constructor public class GetConstructor {public static void main (string[] args) throws Ex ception {getAll ();} Get all constructors private static void GetAll () throws Exception {//1): Gets the object of the class where the constructor is located class<user> Claz = USER.CLASS;//2): Gets all constructors in the object constructor<?>[] con = claz.getconstructors ();//getconstructors () Gets the constructor with public in the class, Returns a constructors array for (constructor<?> Constructor:con) {System.out.println (Constructor);} constructor<?>[] Con1 = Claz.getdeclaredconstructors ();//getdeclaredconstructors () gets all the constructors in the class, regardless of access rights, Returns a constructors array for (constructor<?> constructor:con1) {System.out.println (Constructor);} Gets the constructor for public User () constructor<user> con2 = Claz.getconstructor (); System.out.println (Con2);//Gets the constructor for public User (String name)//NOTE: You must use Getdeclaredconstructor (); Have access to constructor <User> Con3 = Claz.getdeclaredconstructor(String.class, Int.class); System.out.println (Con3);}}

Call the constructor with reflection----> Create Object
Package classinstance;//uses reflection to call the constructor--Create object import java.lang.reflect.constructor;class Peson {public Peson () { System.out.println ("parameterless constructor");} Public Peson (String name) {System.out.println ("parameterized constructor" + name);} Private Peson (String name, int age) {System.out.println ("parameterized constructor" + name + "," + Age);}} public class Cteateobject {public static void main (string[] args) throws Exception {cteate ();} public static void Cteate () throws Exception {//Get constructor object class<peson> Clasz = Peson.class; constructor<?> Con1 = Clasz.getdeclaredconstructor (); constructor<?> Con2 = Clasz.getdeclaredconstructor (String.class); constructor<?> Con3 = Clasz.getdeclaredconstructor (String.class, int.class);//Create Object Con2.newinstance ("Zhang San");// Newinstance (); Creates a new instance of the class represented by this class object//Setting the constructor can access con3.setaccessible (true); Con3.newinstance ("John Doe", 15);}}

Dynamically Loading resource files
Package Classinstance;import Java.io.fileinputstream;import Java.io.ioexception;import java.io.InputStream;import java.util.properties;//Dynamic Load resource file public class Loadresourcedemo {public static void main (string[] args) throws Exception { Text1 (); Text2 ();} The best way to use private static void Text2 () throws Exception {Properties P = new Properties (); ClassLoader loader = Thread.CurrentThread (). Getcontextclassloader (); InputStream instream = Loader.getresourceasstream ("Db.properties");p. Load (instream); SYSTEM.OUT.PRINTLN (P);} private static void Text1 () throws Exception {//General mode Properties P = new properties (); InputStream instream = new FILEINPUTST Ream ("File/db.properties");//p.load (instream); SYSTEM.OUT.PRINTLN (P);}}

Reflection mechanism of Java core class library

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.