Common Scenarios for "reflection (Reflect)" in Java

Source: Internet
Author: User

Brief introduction:

Summarized in IMOOC course: http://www.imooc.com/learn/199

Through a few simple examples, this article introduces the use of class classes, the reflection of methods and member variables, and the understanding of the nature of set generics through reflection.

Use of the 1.Class class

/** * Dynamically load a class using the Java.lang.Class class, compile without checking for class presence and error, run-time check */public class Officebetter {public static void main (string[] args) {args = new string[1]; Scanner input = new Scanner (system.in); Args[0] = Input.next (); try {class<?> C = class.forname ("Dynamic load.") +args[0]); Iofficestart Officestart = (iofficestart) c.newinstance (); Officestart.start ();} catch (ClassNotFoundException | instantiationexception | Illegalaccessexception e) {e.printstacktrace ();} finally{input.close ();}}} Office feature Interface public interface Iofficestart {void start ();} Implement 1public class Word implements iofficestart{@Overridepublic void Start () {System.out.println ("Word...start ...");}} Implement 2public class Excel implements iofficestart{@Overridepublic void Start () {System.out.println ("Excel...start ...");}}

  

2. Obtaining information about a class by object or class name

/** * Get all methods, constructors, variables */public class Classutil {public static void main (string[] args) {Class C1 = Int.cla by class object ss Class C2 = Void.class; System.out.println (C1.getname ()); System.out.println (C2.getname ()); Classutil.printclassmethods (New Double (1.0d)); Classutil.printclassfields (New Integer (1)); Classutil.printclassconstructors (New String ());} /** * Print all methods of the class that the Obj object is in * @param obj */public static void Printclassmethods (Object obj) {//First Gets the class type of Class C = Obj.getclass (); System.out.println (C.getname () + "class-All Method:"),//getmethods returns all public methods, including inherited methods//getdeclaredmethods () returns all methods, Does not include inherited methods method []ms = C.getmethods ();//Traversal collection prints each method, including method return value, method name, method parameter for (int i = 0; i < ms.length; i++) {Method M = ms[i] ;//return type System.out.print (M.getreturntype (). Getsimplename () + "");//Method name System.out.print (m.getname () + "(");// The parameter set Class []args = M.getparametertypes (); for (Class Class1:args) {System.out.print (Class1.getsimplename () + ",");} System.out.println (")");} System.out.println ("\ n");} /** * Print all constructors for the class containing the Obj object */public static void Printclassconstructors (Object obj) {Class c = obj.getclass (); System.out.println (C.getname () + "all constructors for Class:"); Constructor []cs = C.getdeclaredconstructors (); for (int i = 0; i < cs.length; i++) {System.out.print (Cs[i].getname () + " ("); class []paras = Cs[i].getparametertypes (); for (Class Class1:paras) {System.out.print (Class1.getname () + ",");} System.out.println (")");} System.out.println ("\ n");} /** * Prints all variables of the class where the Obj object is located */public static void Printclassfields (Object obj) {Class C = Obj.getclass (); System.out.println (C.getname () + "All member variables of class:"); field[] fields = C.getfields (), for (int i = 0; i < fields.length; i++) {Field field = Fields[i]; System.out.println (Field.gettype (). GetName () + "" + field.getname ());     System.out.println ("\ n");}}

  

3. When a method of a class is obtained through an object, the method is called by reflection

Import Java.lang.reflect.method;public class Main {public static void Main (string[] args) {A A = new A ();//Under Object A to reflect the calling method cl ass<? Extends a> C = a.getclass (); try {//method m1 = C.getmethod ("Print1", New Class[]{string.class,string.class}); Method m1 = C.getmethod ("Print1", string.class,string.class);//method m2 = C.getmethod ("Print2", New class[]{}); Method m2 = C.getdeclaredmethod ("Print2"); M1.invoke (A, "HELLO", "World"); M2.invoke (a);} catch (Exception e) {e.printstacktrace ();}}} Class A{public void Print1 (String a,string b) {System.out.println (a.tolowercase () + "" + b.touppercase ());} public void Print2 () {System.out.println ("Hello World");}}

  

4. Understanding generics by reflection (not considered a scenario)

Import Java.lang.reflect.method;import Java.util.arraylist;public class Main {public static void main (string[] args) { ArrayList List1 = new ArrayList (); arraylist<string> list2 = new arraylist<string> () list2.add ("Hello");//ok//list2.add (1111);// FalseSystem.out.println (list1.getclass () = = List2.getclass ());//output true//because class types are found to be = = by reflection with generics and without generics./ So it is assumed that the essence of generics is to be a reminder before compiling, and after compilation there is no generics//through reflection to verify the try {Method m = List1.getclass (). GetMethod ("Add", Object.class); M.invoke ( List2, 1111); System.out.println (LIST2);//test Add in 1111//for (String string:list2) {//system.out.print (string);//} You cannot traverse for this at this time Object obj:list2) {System.out.print (obj + "");} Discovery can add} catch (Exception e) {//Todo:handle Exception}}}

  

Common Scenarios for "reflection (Reflect)" in Java

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.