"Java" (2) Java reflection

Source: Internet
Author: User

1. Concept

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.


2. Get the Class object

public class ClassDemo1 {public static void main (string[] args) {try {entity foo1 = new Entity ();//Get the class object in two ways: Class C 1 = entity.class; Class C2 = Foo1.getclass (); Class C3 = Class.forName ("com.thr.reflect.Entity"), or C1 or C2, represents the object of class of Entity System.out.println (c1 = = C2);// C3 is also the class object of entity System.out.println (C1 = = C3);} catch (ClassNotFoundException e) {e.printstacktrace ();}}} Class Entity {}
The class objects obtained in three ways are consistent.

We can also create classes with class objects:

Entity en = (entity) c1.newinstance ();

This object can be obtained by using the internal method of the entity just like the object created by new.


3. Dynamic Load Class

First create an interface:

public interface singable {void Sing ();}
then write two implementations of the class:
public class Bird implements singable {@Overridepublic void Sing () {System.out.println ("Bird sing ...");}
public class Cat implements singable {@Overridepublic void Sing () {System.out.println ("Cat sing ...");}}

Finally, the dynamic load class in the main program:

public class World {public static void main (string[] args) {try {Class C = Class.forName (Args[0]); Singable singable = (singable) c.newinstance (); singable.sing ();} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace ();}}}

The full name parameter of the class to pass in at run time.


4. Get method Information

First look at the class object of the basic data type:

public class ClassDemo2 {public static void main (string[] args) {class[] cs = new class[] {int.class, string.class, Doubl E.class,double.class, Void.class, Class.class};for (class C:cs) {System.out.println (C.getname ()); System.out.println (C.getsimplename ());}}}
We write a tool method that gets the method of the class:
public static void Printclassmethods (Object obj) {//First Gets the class object class C = Obj.getclass ();//Gets the name of the class System.out.println (" The name of the class is: "+ c.getname ());//Gets the method of the class, the object of which is a member method, which is obtained through GetMethods () is the method of all public, including the inheritance from the parent class//Getdeclaredmethods () gets all the methods of that class of its own life, without asking access rights method[] ms = C.getmethods (); for (Method m:ms) {//Get return value type class ReturnType = M.getreturntype (); S Ystem.out.print (Returntype.getname () + "");//Get Method name System.out.print (m.getname () + "(");//get parameter type class[] Paramtypes = M.getparametertypes (); for (Class type:paramtypes) {System.out.print (Type.getname () + ",");} System.out.println (")");}}
Use it:
public static void Main (string[] args) {string s = new String (); Classutil.printclassmethods (s); Integer i = 1; Classutil.printclassmethods (i);}

5. Get member variables and constructor information

Get member Variable information:

public static void Printclassfields (Object obj) {//First Get Class object class C = Obj.getclass ();//Use GetFields () Gets the member variable information for all public, using Getdeclaredfields to get the member variable information declared by the class itself, without asking access rights field[] fs = C.getdeclaredfields (); for (Field F:fs) { Gets the type of the member variable class FieldType = F.gettype (); String typeName = Fieldtype.getname ();//Gets the member variable's name string filedname = F.getname (); System.out.println (TypeName + "" + Filedname);}}
Get Construction method information:
public static void Printclassconstructor (Object obj) {//First gets class object class C = Obj.getclass (); Constructor[] cons = C.getdeclaredconstructors (); for (Constructor con:cons) {//Get method name System.out.print (con.getname () + " (");//get parameter type class[] paramtypes = Con.getparametertypes (); for (Class type:paramtypes) {System.out.print (Type.getname ( ) + ",");} System.out.println (")");}}

6. Basic operation of method reflection

All method objects have an invoke method that we call Method.invoke (object, argument list) to execute the method:

public class MethodDemo1 {public static void main (string[] args) {try {//get print (int, int) Method A = new A (); Class C = A.getclass (); Method M1 = C.getmethod ("Print", Int.class, Int.class);//execute method, use O to accept the return value//If there is a return value, then object is the type of the return value; no return value returns the Nullobject O1 = M1.invoke (A, 10, 10);//Gets the print (string, String) method methods m2 = C.getmethod ("Print", new class[] {string.class,string.c Lass}); object O2 = M2.invoke (A, "S1", "S2");//Gets the print () method m3 = C.getmethod ("print"); object O3 = M3.invoke (a); System.out.println (O1); System.out.println (O2); System.out.println (O3);} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( InvocationTargetException e) {e.printstacktrace ();}}} Class A {public void print () {System.out.println ("Hello");} public int print (int a, int b) {System.out.println (A + b); return a + b;} public string Print (string A, STring b) {System.out.println (a.touppercase () + "," + b.tolowercase ()); return a + b;}} 

7. The nature of generics
public static void Main (string[] args) {List list1 = new ArrayList (); list<string> list2 = new arraylist<string> (); Class C1 = List1.getclass (); Class C2 = List2.getclass (); SYSTEM.OUT.PRINTLN (C1 = = C2);//The reflected operation is a compile-after operation//C1==C2 is true to indicate that the generic type of the compiled collection after compilation is de-generalized//Java collection of generics is to prevent the wrong input, only in the compilation phase valid, Bypassing the compilation is not valid//We can bypass the compilation method M;try {m = C1.getmethod ("Add", object.class) by means of reflection, M.invoke (List1, 100); System.out.println (List1.size ()); System.out.println (List1);} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( InvocationTargetException e) {e.printstacktrace ();}}
Through this example, we can see that the reflection mechanism through Java can bypass the compilation, which is executed at runtime, and it is natural to bypass the generic type of the collection.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Java" (2) Java reflection

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.